-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Open
Description
898 - Includes
Includes requires us to start thinking abstractly about how to leverage recursion in writing comprehensive TypeScript types. Although it's difficult at first, don't worry. We're going to be doing quite a lot of recursion in future challenges.
🎥 Video Explanation
🔢 Code
import type { Equal, Expect, IsFalse, IsTrue } from './test-utils'
type trueCases = [
Expect<IsTrue<
Includes<['Kars', 'Wamuu', 'Santana'], 'Kars'>
>>,
Expect<IsTrue<
Includes<[1, 2, 3, 5, 6, 7], 7>
>>,
Expect<IsTrue<
Includes<[1, 2, 3], 2>
>>,
Expect<IsTrue<
Includes<[1, 2, 3], 1>
>>,
Expect<IsTrue<
Includes<[false, 2, 3, 5, 6, 7], false>
>>
];
type falseCases = [
Expect<IsFalse<
Includes<['Kars', 'Wamuu', 'Santana'], 'Dio'>
>>,
Expect<IsFalse<
Includes<[1, 2, 3, 5, 6, 7], 4>
>>,
Expect<IsFalse<
Includes<[{}], { a: 'A' }>
>>,
Expect<IsFalse<
Includes<[boolean, 2, 3, 5, 6, 7], false>
>>,
Expect<IsFalse<
Includes<[true, 2, 3, 5, 6, 7], boolean>
>>,
Expect<IsFalse<
Includes<[{ a: 'A' }], { readonly a: 'A' }>
>>,
Expect<IsFalse<
Includes<[{ readonly a: 'A' }], { a: 'A' }>
>>,
Expect<IsFalse<
Includes<[1], 1 | 2>
>>,
Expect<IsFalse<
Includes<[1 | 2], 1>
>>,
Expect<IsFalse<
Includes<[null], undefined>
>>,
Expect<IsFalse<
Includes<[undefined], null>
>>,
];
// ============= Your Code Here =============
type Includes<T extends unknown[], U> =
T extends [infer Head, ...infer Tail]
? Equal<U, Head> extends true
? true
: Includes<Tail, U>
: false
;
type Includes<T extends unknown[], U> =
boolean extends {
[I in keyof Omit<T, "length"> as
Equal<T[I], U> extends true
? I
: never
]: T[number]
}
? false
: true
;
// This way creates an object with values that are booleans.
// then you turn that object's values into a boolean union
// if the union includes true, then it will not extend false
type Includes<T extends unknown[], U> =
{ [K in keyof T]: Equal<T[K], U> } extends Record<number, false>
? false
: true
;
// same as above, but unwraps the object
type Includes<T extends unknown[], U> =
{ [K in keyof T]: Equal<T[K], U> }[number] extends false
? false
: true
;➕ More Solutions
For more video solutions to other challenges: see the umbrella list! #21338
Metadata
Metadata
Assignees
Labels
No labels