Closed
Labels
Working as IntendedThe behavior described is the intended behavior; this is not a bugThe behavior described is the intended behavior; this is not a bug
Description
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)
Metadata
Metadata
Assignees
Labels
Working as IntendedThe behavior described is the intended behavior; this is not a bugThe behavior described is the intended behavior; this is not a bug
Activity
jvitkauskas commentedon Jun 14, 2017
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 commentedon Jun 14, 2017
This is working as intended. Literal types are widened when they are inferred for mutable locations (such as the
valueproperty in your example) unless you have a type annotation or type assertion indicating otherwise.ahejlsberg commentedon Jun 14, 2017
See #10676 for more details.