Closed brandonmcconnell closed 1 year ago
There are several goals I am hoping to achieve here, with these type helpers:
const a: string & Not<"test"> = "test"; // ^ TS should complain
Ensure a type is not in another grouped type like an array or object
Array example
const forbiddenStrings = ['bad', 'worse', 'worst'] as const; const a: string & NotIn<typeof forbiddenStrings> = "bad"; // ^ TS should complain
Object keys example
const forbiddenStrings = { bad: 1, worse: 2, worst: 3 } as const; const a: string & NotIn<keyof typeof forbiddenStrings> = "bad"; // ^ TS should complain
const wordsA: string[] & NoIntersect<typeof wordsB, keyof typeof wordsC> = ['a', 'b', 'c'] as const; // ^ TS should complain const wordsB: string[] & NoIntersect<typeof wordsA, keyof typeof wordsC> = ['d', 'e', 'f'] as const; // ^ TS should complain const wordsC: string[] & NoIntersect<typeof wordsA, typeof wordsB> = { g: 1, h: 2, i: 3 } as const; // ^ TS should complain
I'm' not sure what the API for this would look like, likely not what I showed above but something more argument-based like this…
type SomeType = NoIntersect<typeof wordsB, keyof typeof wordsC>;
…if the base type can be inferred, otherwise passed explicitly as the first arg like this:
type SomeType = NoIntersect<string[], typeof wordsB, keyof typeof wordsC>;
This is not possible in typescript. Feature request was rejected long time ago from TS team : https://github.com/microsoft/TypeScript/issues/47178
There are several goals I am hoping to achieve here, with these type helpers:
Ensure a type is not in another grouped type like an array or object
Array example
Object keys example
I'm' not sure what the API for this would look like, likely not what I showed above but something more argument-based like this…
…if the base type can be inferred, otherwise passed explicitly as the first arg like this: