Skip to content
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

Type IsNever #40248

Closed
macabeus opened this issue Aug 25, 2020 · 1 comment
Closed

Type IsNever #40248

macabeus opened this issue Aug 25, 2020 · 1 comment

Comments

@macabeus
Copy link

Search Terms

never, distributive conditional type

Suggestion

As described at this issue, this behaviour is the expected:

type IsNever<T> = (
  T extends never
    ? true
    : false
)

let foo: IsNever<1> // false
let bar: IsNever<never> // never

But since it always returning false or never is complicated to compound more complex types, for example:

type ArrayHasLessThanThreeElements<T> = (
    IsNever<Extract<'2', keyof T>>
)

let a: ArrayHasLessThanThreeElements<[1, 2, 3]> // false
let b: ArrayHasLessThanThreeElements<[1, 2]> // never, but the expected type is "true"

Use Cases

It is useful when you need to compound types and use something like T extends never.
Since if T is never the truthy clausure isn't run, it's very complicated to compound types at this case.

Examples

Let's say that we have the new utility type IsNever from TS:

type ArrayHasLessThanThreeElements<T> = (
    IsNever<Extract<'2', keyof T>>
)

let a: ArrayHasLessThanThreeElements<[1, 2, 3]> // false
let b: ArrayHasLessThanThreeElements<[1, 2]> // true
@yume-chan
Copy link
Contributor

Just scroll down a little bit to #31751 (comment) you will find how to do IsNever as your Intended.

type IsNever<T> = [T] extends [never] ? true: false;

type ArrayHasLessThanThreeElements<T> = (
    IsNever<Extract<'2', keyof T>>
)

let a: ArrayHasLessThanThreeElements<[1, 2, 3]> // false
let b: ArrayHasLessThanThreeElements<[1, 2]> // true

(playground)

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