Skip to content

[Feature Request]: Not, NotIn, and NoIntersect handlers for validation and duplicate checks #74

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

Closed
brandonmcconnell opened this issue Feb 28, 2023 · 1 comment

Comments

@brandonmcconnell
Copy link

brandonmcconnell commented Feb 28, 2023

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>;
@ecyrbe
Copy link
Collaborator

ecyrbe commented Feb 28, 2023

This is not possible in typescript. Feature request was rejected long time ago from TS team : microsoft/TypeScript#47178

@ecyrbe ecyrbe closed this as completed Feb 28, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants