Description
I asked question about resulting type of the object literal at stackoverflow.
From specification:
When an object literal is contextually typed by a type that includes a string index signature, the resulting type of the object literal includes a string index signature with the union type of the types of the properties declared in the object literal, or the Undefined type if the object literal is empty
First, it sounds like some entity that has type can redefine it if it meets object literal.
Second, maybe it is all about hidden conversations at expression trees?
The question:
Is there any places in code where I can see resulting type of object literal in action?
I have got an answer:
declare const str: 'a' | 'b';
let foo = { a: 1, b: "2" }[str]; //type of foo string | number
Ok.
I look at following part of spec.
A bracket notation property access of the form
object [ index ]
where object and index are expressions, is used to access the property with the name computed by the index expression on the given object. A bracket notation property access is processed as follows at compile-time:
If index is a string literal or a numeric literal and object has an apparent property (section 3.11.1) with the name given by that literal (converted to its string representation in the case of a numeric literal), the property access is of the type of that property.
Otherwise, if object has an apparent numeric index signature and index is of type Any, the Number primitive type, or an enum type, the property access is of the type of that index signature.
Otherwise, if object has an apparent string index signature and index is of type Any, the String or Number primitive type, or an enum type, the property access is of the type of that index signature.
Otherwise, if index is of type Any, the String or Number primitive type, or an enum type, the property access is of type Any.
Otherwise, the property access is invalid and a compile-time error occurs.
The type of str
is union of string literals and there is no branch for this case above.
And I didn't see any index signatures in the example (from answer).
But it does compile.
Could someone elaborate on this topic, please.