yunliuyan / type-challenges

typescript-challenges
0 stars 2 forks source link

00021-easy-includes #21

Open yunliuyan opened 11 months ago

yunliuyan commented 11 months ago

Includes 简单 #array

by null @kynefuk

接受挑战    English 日本語 한국어

在类型系统里实现 JavaScript 的 Array.includes 方法,这个类型接受两个参数,返回的类型要么是 true 要么是 false

例如:

type isPillarMen = Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Dio'> // expected to be `false`

返回首页 分享你的解答 查看解答
yunliuyan commented 11 months ago

思路

number将元素遍历出来

代码实现

type Includes<T extends readonly any[], U extends any> = U extends T[number] ? true : false

type isPillarMen = Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Dio'> // expected to be `false`
Janice-Fan commented 11 months ago
type Includes<T extends readonly any[], P extends any> = {
    [k in T[number]]: true;
}[P] extends true ? true : false;

type isPillarMen = Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Dio'> // expected to be `false`
Naparte commented 11 months ago

// 在类型系统里实现 JavaScript 的 Array.includes 方法,这个类型接受两个参数,返回的类型要么是 true 要么是 false。

type Includes<T extends any[], K> = K extends T[number] ? true : false;

type isPillarMen = Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'xxx'> // expected to be `false`