如何在typescript中创建只接受具有两个或多个元素的数组的类型?

needsTwoOrMore(["onlyOne"]) // should have error
needsTwoOrMore(["one", "two"]) // should be allowed
needsTwoOrMore(["one", "two", "three"]) // should also be allowed

最佳答案

这可以通过以下类型来实现:

type ArrayTwoOrMore<T> = {
    0: T
    1: T
} & Array<T>

declare function needsTwoOrMore(arg: ArrayTwoOrMore<string>): void

needsTwoOrMore(["onlyOne"]) // has error
needsTwoOrMore(["one", "two"]) // allowed
needsTwoOrMore(["one", "two", "three"]) // also allowed

TypeScript Playground Link

10-07 17:37