-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Labels
1042answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English
Description
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
🔢 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
Labels
1042answerShare answers/solutions to a questionShare answers/solutions to a questionenin Englishin English