Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spurious "index signature incompatible" error for function returning an object literal expression #862

Closed
NoelAbrahams opened this issue Oct 9, 2014 · 2 comments
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead

Comments

@NoelAbrahams
Copy link

Hi,

TypeScript Version: 1.1.0.1

Here is the repro:

interface Foo {
    [index: string]: any;
    name: string;       
}

// Case 1: no error
var f1: Foo = {
        name: 'FooOne',
};

// Case 2: no error 
var f2 = function(): Foo {
    return {
        name: 'FooTwo',
    };
}

// Case 3:
// Compiler Error: error TS2322: Build: Type '{ name: string; }' is not 
   // assignable to type 'Foo'
// IDE Error: Cannot convert '{ name: string; }' to 'Foo':  Index signatures 
   // of types '{ name: string; }' and 'Foo' are incompatible.
var f3 = (): Foo => ({
        name: 'FooThree',
});

The expected result is there to be no error, since the object literal in the last case is indexable by string to return any.

@basarat
Copy link
Contributor

basarat commented Oct 9, 2014

The expected result is there to be no error

👍 since f3 is effectively same as f2.

@RyanCavanaugh RyanCavanaugh added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Oct 9, 2014
@RyanCavanaugh
Copy link
Member

Contextual types do not flow into parentheses, so the return expression of the function expression initializing f3 is not contextually typed by Foo.

See also http://stackoverflow.com/questions/22077023/why-cant-i-indirectly-return-an-object-literal-to-satisfy-an-index-signature-re

@microsoft microsoft locked and limited conversation to collaborators Jun 18, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead
Projects
None yet
Development

No branches or pull requests

3 participants