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

#00898 include #11

Open
pkc918 opened this issue Aug 11, 2023 · 0 comments
Open

#00898 include #11

pkc918 opened this issue Aug 11, 2023 · 0 comments

Comments

@pkc918
Copy link
Owner

pkc918 commented Aug 11, 2023

题目

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

// test
Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Kars'> // true
Includes<['Kars', 'Esidisi', 'Wamuu', 'Santana'], 'Dio'> // false
Includes<[1, 2, 3, 5, 6, 7], 7> // true
Includes<[1, 2, 3, 5, 6, 7], 4> // false
Includes<[1, 2, 3], 2> // true
Includes<[1, 2, 3], 1> // true
Includes<[{}], { a: 'A' }> // false
Includes<[boolean, 2, 3, 5, 6, 7], false> // false
Includes<[true, 2, 3, 5, 6, 7], boolean> // false
Includes<[false, 2, 3, 5, 6, 7], false> // true
Includes<[{ a: 'A' }], { readonly a: 'A' }> // false
Includes<[{ readonly a: 'A' }], { a: 'A' }> // false
Includes<[1], 1 | 2> // false
Includes<[1 | 2], 1> // false
Includes<[null], undefined> // false
Includes<[undefined], null> // false

实现 js 中的 includes 的功能,返回boolean

答案

type IsEqual<T, U> =
    (<G>() => G extends T ? 1 : 2) extends (<G>() => G extends U ? 1 : 2) ? true : false

type Includes<T extends readonly any[], U> = T extends [infer First, ...infer Rest] ? IsEqual<First, U> extends true ? true : Includes<Rest, U> : false

讲解

先不用看 IsEqual,我们可以看到,我们首先是利用了每次取第一个值,判断是否和第一个值相等。用这样的方式进行递归,直到为空,IsEqual 实现以及讲解(可以看看官方的探讨)[https://github.com/microsoft/TypeScript/issues/27024]

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

1 participant