这是indexloc提供的服务,不要输入任何密码
Skip to content

1042 - IsNever (🎥 Video Explanation and Solution) #22791

@dimitropoulos

Description

@dimitropoulos

1042 - IsNever

IsNever is definitely one of my favorite challenges. This is definitely one of the more theoretical challenges where you can learn a lot that's useful in other situations. Highly recommend this one.

🎥 Video Explanation

Release Date: 2023-02-10 19:00 UTC

IsNever

🔢 Code

// ============= Test Cases =============
import type { Expect, IsFalse, IsTrue } from './test-utils'

type cases = [
  Expect<IsTrue<IsNever<never>>>,

  Expect<IsFalse<IsNever<never | string>>>,
  Expect<IsFalse<IsNever<''>>>,
  Expect<IsFalse<IsNever<undefined>>>,
  Expect<IsFalse<IsNever<null>>>,
  Expect<IsFalse<IsNever<[]>>>,
  Expect<IsFalse<IsNever<{}>>>,
];

// ============= Your Code Here =============
// see https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types


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

// ============== Alternatives ==============

/*
|     | [never] | never[] |
| --- | ------- | ------- |
| [T] | ✓ (0)   | ✓ (1)   |
| T[] | ✓ (2)   | ✓ (3)   |
*/
type IsNever0<T> = [T] extends [never] ? true : false;
type IsNever1<T> = [T] extends never[] ? true : false;
type IsNever2<T> = T[] extends [never] ? true : false;
type IsNever3<T> = T[] extends never[] ? true : false;


// adds symmetry.  easy to see what they were thinking
type IsNever<T> =
  [T, never] extends [never, T]
  ? true
  : false;

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

type IsNever<T> =
  T | true extends true
    ? true
    : false;

// same as above, but flips the condition
type IsNever<T> =
  T | false extends false
  ? false extends T
    ? false
    : true
  : false;

// ================== NOPE ==================
// so, `never` can not extend `never`,
// but, a tuple containing only never (`[never]`)
// can extend another tuple (again containing never)
type IsNever<T> =
  T extends never
  ? true
  : false;

// works, but uses invalid builtin: `Exclude`
type IsNever<T> =
  Exclude<T, never> extends never
  ? true
  : false;

➕ More Solutions

For more video solutions to other challenges: see the umbrella list! #21338

Metadata

Metadata

Assignees

No one assigned

    Labels

    1042answerShare answers/solutions to a questionenin English

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions