[Typescript] The naked type
So what is a nake type?
Example:
type UnionToIntersection<T> =
(T extends any ? (x: T) => any : never) //...
We check T
in a sub-type condition,
T extends any ?...
And T is not wrapping with anything:
type Naked<T> = T extends ... // naked!
type NotNaked<T> = { o: T } extends ... // not naked!
Feature of The naked type
If T
is a union type, Typescript run each item of the T
against the condition.
So with a naked type, a conditional of union types becomes a union of conditional types, For example:
type WrapNaked<T> =
T extends any ? { o: T } : never;
type Foo = WrapNaked<string | number | boolean>
// equals to
type Foo = WrapNaked<string> | WrapNaked<number> | WrapNaked<boolean>
// equals to
type Foo =
string extends any ? { o: string } : never |
number extends any ? { o: number } : never |
boolean extends any ? { o: boolean } : never
type Foo =
{ o: string } | { o: number } | { o: boolean }
As compared to the non-naked version:
type WrapNaked<T> =
{ o: T } extends any ? { o: T } : never
type Foo = WrapNaked<string | number | boolean>
// A non Naked type, so this equals to
type Foo = { o: string | number | boolean } extends any ? { o: string | number | boolean } : never
type Foo = { o: string | number | boolean }