Closed
Description
TypeScript Version: 2.9.0-dev.20180501
Search Terms:
union type does not match conditional type
Code
function test<T>(arg: T): T extends any[] ? any[] : number {
return Array.isArray(arg) ? [] : 1;
}
Expected behavior:
No errors and for the result of test()
to be known as array or number.
It's possible there is a good reason for this behavior, but it certainly seems like it should work, to me (with Typescript as my first type annotated language).
Actual behavior:
Error:
Type 'undefined[] | 1' is not assignable to type 'T extends any[] ? any[] : number'.
Type 'undefined[]' is not assignable to type 'T extends any[] ? any[] : number'.
Related Issues:
Unknown?
Metadata
Metadata
Assignees
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
marcellerusu commentedon May 1, 2018
Afaik, ternary operator doesn't work on type level. It also doesn't make much sense what it'd actually do here imo.
What's wrong with doing it like
--
EDIT: ignore me, didn't realize type level ternary exists
mhegazy commentedon May 1, 2018
Similar to #22984. This is a design limitation of the current implementation, the relationship between the resulting types and the conditional type is lost through the ternary operation. the compiler can not verify the relationship at the moment.
The alternative is to use overloads to model your example.
kevinbeal commentedon May 1, 2018
@MarcelRusu
Conditional types (with ternary expressions) were added in 2.8
I have a situation where I have this interface:
I want variables implementing this interface to be aware of the
controls
field is specifically beingFormGroup
orFormArray
.kevinbeal commentedon May 1, 2018
@mhegazy Okay, you can close this then, but it doesn't work for my actual use case.
I just offered a simplified example.
Is another implementation planned?
mhegazy commentedon May 1, 2018
This example might be related to #23132.
mhegazy commentedon May 1, 2018
we continue to add new inferences, so it is possible.
mhegazy commentedon May 1, 2018
Depending on how you are using
ControlResult
, an alternative in your other example is to lift the union type over your whole type.typescript-bot commentedon May 16, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.