TypeScript array with minimum length

后端 未结 3 1490
野趣味
野趣味 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 15:54
    type FixedTwoArray<T> = [T,T]
    interface TwoOrMoreArray<T> extends Array<T> {
        0: T
        1: T
    }
    
    let x: FixedTwoArray<number> = [1,2];
    let y: TwoOrMoreArray<string> = ['a','b','c'];
    
    

    TypeScript Playground

    0 讨论(0)
  • 2020-12-11 16:05

    This is an old question and the answer is fine (it helped me as well), but I just stumbled across this solution as well while playing.

    I had already defined a typed Tuple (type Tuple<T> = [T, T];), and then below that, I had defined array of two or more as described above (type ArrayOfTwoOrMore<T> = { 0: T, 1: T } & T[];).

    It occurred to me to try using the Tuple<T> structure in place of { 0: T, 1: T }, like so:

    type ArrayOfTwoOrMore<T> = [T, T, ...T[]];

    And it worked. Nice! It's a little more concise and perhaps able to be clearer in some use-cases.

    Worth noting is that a tuple doesn't have to be two items of the same type. Something like ['hello', 2] is a valid tuple. In my little code snippet, it just happens to be a suitable name and it needs to contain two elements of the same type.

    0 讨论(0)
  • 2020-12-11 16:06

    This can be accomplished with a type like:

    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

    0 讨论(0)
提交回复
热议问题