You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Extending empty tuple in generic functions causes compiler to infer arrays as tuples #31434
Search Terms:
empty tuple, type inference, generic function
Code
Basically I'm writing a generic function with dynamic type mapping. I think this use case is pretty common for database drivers and JSON validators and I found some related issues. There is a workaround and I want to confirm whether it is intended behavior or a bug.
interfaceTypeMap{STRING: string;NUMBER: number;}typeMapTypes<T>={[PinkeyofT]: T[P]extendskeyofTypeMap ? TypeMap[T[P]] : never};declarefunctionfromArray<TextendsReadonlyArray<keyofTypeMap>>(types: T,params: MapTypes<T>): void;fromArray(['STRING','NUMBER','STRING'],['abc',123,'xyz']);// ok// the default behavior is to infer types in array as type unionfromArray(['STRING','NUMBER','STRING'],['abc','123','xyz']);// no errorfromArray(['STRING','NUMBER','STRING']asconst,['abc','123','xyz']);// errordeclarefunctionfromTuple<Textends([]|ReadonlyArray<keyofTypeMap>)>(types: T,params: MapTypes<T>): void;fromTuple(['STRING','NUMBER','STRING'],['abc',123,'xyz']);// ok// T extends([]|MyType) cases the compiler to infer array as tuplefromTuple(['STRING','NUMBER','STRING'],['abc','123','xyz']);// errorfromTuple(['STRING','NUMBER','STRING']asconst,['abc','123','xyz']);// error
Expected behavior:
Type of the array literal is inferred as array of union type.
Actual behavior:
Type of the array literal is inferred as tuple when T extends []|MyType is used in generic function.
I'd prefer it to be the expected behavior, but I didn't find any tests for that use case.
Can I add some tests for this behavior then? I wasn't able to find anything similar by grepping tests directory (grep 'extends \[\]' -r tests/).
There are tests that check a combination of two tuples, but not a combination of a tuple and array.
Activity
ahejlsberg commentedon May 16, 2019
This is working as intended. We only infer tuple types when the contextual type is or contains a tuple-like type.
ipotuzhnov commentedon May 16, 2019
Anders Hejlsberg (@ahejlsberg) Great, thank you for confirming.
Can I add some tests for this behavior then? I wasn't able to find anything similar by grepping tests directory (
grep 'extends \[\]' -r tests/).There are tests that check a combination of two tuples, but not a combination of a tuple and array.
ahejlsberg commentedon May 16, 2019
Yes, it is the intended behavior. See #27179 (comment) for the recommended pattern.
ipotuzhnov commentedon May 16, 2019
Thank you for the link. I think I've seen that issue, but didn't go through all comments.