TypeScript array with minimum length

后端 未结 3 1511
野趣味
野趣味 2020-12-11 15:29

How can you create a type in TypeScript that only accepts arrays with two or more elements?

needsTwoOrMore([\"onlyOne\"]) // should have error
needsTwoOrMore         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 16:06

    This can be accomplished with a type like:

    type ArrayTwoOrMore = {
        0: T
        1: T
    } & Array
    
    declare function needsTwoOrMore(arg: ArrayTwoOrMore): void
    
    needsTwoOrMore(["onlyOne"]) // has error
    needsTwoOrMore(["one", "two"]) // allowed
    needsTwoOrMore(["one", "two", "three"]) // also allowed
    

    TypeScript Playground Link

提交回复
热议问题