Implement Exclude, Extract
Daisho Komiyama edited this page Mar 3, 2024
·
3 revisions
type _Exclude<T, U> = T extends U ? never : T;
type _Extract<T, U> = T extends U ? U : never;
type MyColor = | "me" | "you" |[number, number] | { red: "#ff0", yellow: "#f00"}
type MyColor2 = _Exclude<MyColor, string>
// ^ type MyColor2 = [number, number] | {red: "#ff0"; yellow: "#f00";}
// all types except "me" | "you"
type MyColor3 = _Extract<MyColor, string>
// ^ type MyColor3 = string
Note that while this implementation resembles what TSC does, they are not exactly the same. For example;
// My fake Extract
type MyColor4 = _Extract<MyColor, "me" | "yous">
// ^ type MyColor4 = "me" | "yous" <- wrong!
// Real Extract
type MyColor5 = Extract<MyColor, "me" | "yous">
// ^ type MyColor5 = "me" <- correct!