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
55 - Union to Intersection #122
Comments
type UnionToIntersection<U> = (U extends any ? (arg: U) => any : never) extends ((arg: infer I) => void) ? I : never
type I = UnionToIntersection<'foo' | 42 | true> // never
type A = 'foo' | 42 | true
type B = A extends any ? (arg: A) => any : never // (arg: A) => any
type C = B extends ((arg: infer I) => void) ? I : never // 'foo' | 42 | true
type D = 'foo' & 2 & true // never Hi, @githubxiaowen ,I try your solution in my editor.It works when all statements combined as a type template.But When I separate those statements into three statements in order to figure out what mechanism your solution is based on, it didn't work as expect. Could you give me more hints to understand the underlying magic of the solution. (I have read the link you attached above.) BTW, do you know the reason why the three separated statement doesn't work the same as the template type ? |
@Sociosarbis It is because the magic of this solution is given a type like |
amazing! |
If the intersection for a field is never, you can't provide a value for the object anymore. type t = UnionToIntersection<{a: number, b: number} | {a: number, b: string}>;
const t1: t = {a: 1}; // Property 'b' is missing in type '{ a: number; }' but required in type '{ a: number; b: number; }'
const t2: t = {a: 1, b: 1}; // Type 'number' is not assignable to type 'never'.
type NonNeverKeys<T> = { [K in keyof T]: T[K] extends never ? never : K }[keyof T];
type StripNever<T> = T extends object ? { [K in NonNeverKeys<T>]: StripNever<T[K]> } : T;
const t3: StripNever<t> = {a: 1}; // ok |
The solution is amazing, however, i think write as below may be understood more easily
And what does the |
I was wondering the exact same thing, so I turned to SO. |
an answer with clear explanations. thx @kstratis |
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#type-inference-in-conditional-types
The text was updated successfully, but these errors were encountered: