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

Type inference problems when using string literal types #16523

Closed
jvitkauskas opened this issue Jun 14, 2017 · 3 comments
Closed

Type inference problems when using string literal types #16523

jvitkauskas opened this issue Jun 14, 2017 · 3 comments
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug

Comments

@jvitkauskas
Copy link

jvitkauskas commented Jun 14, 2017

TypeScript Version: 2.3.4

Code

function example(parameter: { value: "a" }) { // Function requires argument with string literal
    return;
}

var myObject = {
    value: "a" // TS infers value to be string here, causing problems passing this object to function
};

example(myObject); // Error: Argument of type '{ value: string; }' is not assignable to parameter of type 'ObjectType'. Types of property 'value' are incompatible. Type 'string' is not assignable to type '"a"'.

Expected behavior:
No compiler error

Actual behavior:
Compiler error (see self-contained example)

@jvitkauskas
Copy link
Author

I realize workaround exists for this (just specify type explcitly for myObject), but one of my colleagues ran into this issue while using 3rd party library and was puzzled by this behavior.

Since workarounds are possible, this probably is not a high priority issue, but maybe there's some possibility to explore more flexible type inference for TypeScript project.

@ahejlsberg
Copy link
Member

ahejlsberg commented Jun 14, 2017

This is working as intended. Literal types are widened when they are inferred for mutable locations (such as the value property in your example) unless you have a type annotation or type assertion indicating otherwise.

@ahejlsberg ahejlsberg added the Working as Intended The behavior described is the intended behavior; this is not a bug label Jun 14, 2017
@ahejlsberg
Copy link
Member

See #10676 for more details.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Working as Intended The behavior described is the intended behavior; this is not a bug
Projects
None yet
Development

No branches or pull requests

2 participants