题目
创建一个通用的 Length,接受一个 readonly 的数组,返回这个数组的长度。
type tesla = ['tesla', 'model 3', 'model X', 'model Y']type spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT']type teslaLength = Length<tesla> // expected 4type spaceXLength = Length<spaceX> // expected 5
单元测试
import { Equal, Expect } from '@type-challenges/utils'const tesla = ['tesla', 'model 3', 'model X', 'model Y'] as constconst spaceX = ['FALCON 9', 'FALCON HEAVY', 'DRAGON', 'STARSHIP', 'HUMAN SPACEFLIGHT'] as consttype cases = [Expect<Equal<Length<typeof tesla>, 4>>,Expect<Equal<Length<typeof spaceX>, 5>>,// @ts-expect-errorLength<5>,// @ts-expect-errorLength<'hello world'>,]import { Equal, Expect } from '@type-challenges/utils'type cases = [Expect<Equal<First<[3, 2, 1]>, 3>>,Expect<Equal<First<[() => 123, { a: string }]>, () => 123>>,Expect<Equal<First<[]>, never>>,Expect<Equal<First<[undefined]>, undefined>>]
通过 JS 解题
function getLength (arr) {if(!Array.isArray(arr)) return;return arr.length;}
