rimo030 / type-challenges

Collection of TypeScript type challenges with online judge
https://tsch.js.org/
MIT License
3 stars 0 forks source link

no - 5153 IndexOf #39

Open rimo030 opened 6 months ago

rimo030 commented 6 months ago
type IndexOf<T extends any[], U extends any, R extends any[] = []> = T extends [infer first, ...infer rest]
  ? (<E>()=> E extends U ? 1 : 2) extends (<E>() => E extends first ? 1 : 2)  
    ? R['length']
    : IndexOf<rest, U, [...R, first]>
  : -1
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<IndexOf<[1, 2, 3], 2>, 1>>,
  Expect<Equal<IndexOf<[2, 6, 3, 8, 4, 1, 7, 3, 9], 3>, 2>>,
  Expect<Equal<IndexOf<[0, 0, 0], 2>, -1>>,
  Expect<Equal<IndexOf<[string, 1, number, 'a'], number>, 2>>,
  Expect<Equal<IndexOf<[string, 1, number, 'a', any], any>, 4>>,
  Expect<Equal<IndexOf<[string, 'a'], 'a'>, 1>>,
  Expect<Equal<IndexOf<[any, 1], 1>, 1>>, 
]
rimo030 commented 6 months ago
(<E>()=> E extends U ? 1 : 2) extends (<E>() => E extends first ? 1 : 2)  

any는 Equal<X,Y>의 작동방식을 이해하면 검증할 수 있다.

관련 내용 링크를 첨부합니다.