-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Conditional types expand variants #24969
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
Comments
type Wrap<V = undefined> = [V] extends [{}] ? {value: V} : {};
type BooleanWrap = Wrap<boolean>;
const coinFlip: BooleanWrap = { value: Math.random() > 0.5 }; conditional types are distributive by default. To disable that, simply make the checked type not-a-bare-type-parameter, as above. |
@weswigham beat me by seconds. We should seed a StackOverflow question on this |
This works for me. Thanks! Sorry for the bother. Is there some documentation that I'm missing about the bracket notation? |
It's just the usual tuple syntax; any other wrapping of the type parameter would work, e.g. |
Oh and I should add, all types extend |
As an aside, I had to negate the predicate:
I don't want |
TypeScript Version: 3.0.0-dev.20180609
Search Terms: conditional types, type inference, union, boolean
Code
Expected behavior: The assignment to
coinFlip
should work.Actual behavior: I get the compiler error:
The type of
BooleanWrap
should ideally be resolved to{ value: boolean; }
, but it is resolved to{ value: false; } | { value: true; }
. The same thing happens with any type union.Playground Link: https://www.typescriptlang.org/play/index.html#src=type%20Wrap%3CV%20%3D%20undefined%3E%20%3D%20V%20extends%20%7B%7D%20%3F%20%7Bvalue%3A%20V%7D%20%3A%20%7B%7D%3B%0Atype%20BooleanWrap%20%3D%20Wrap%3Cboolean%3E%3B%0Aconst%20coinFlip%3A%20BooleanWrap%20%3D%20%7B%20value%3A%20Math.random()%20%3E%200.5%20%7D%3B
Related Issues: #24085
The text was updated successfully, but these errors were encountered: