[Feature Request]: `Not`, `NotIn`, and `NoIntersect` handlers for validation and duplicate checks
brandonmcconnell opened this issue · comments
There are several goals I am hoping to achieve here, with these type helpers:
-
Ensure a type is not another type
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
-
Compare objects of different types to ensure none contain the same keys or elements (in the case of arrays)
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 : microsoft/TypeScript#47178