Typescript: Array with min length, and more

Created on 19 Apr 2018  路  5Comments  路  Source: microsoft/TypeScript



TypeScript Version: 2.7.0-dev.201xxxxx


Search Terms:

Code

need something like [string, string, ...argv] or [string, string] & string[]

abc(['', '', ''])

function abc(data: [string, string] & string[]){}

Expected behavior:

allow a array with length >= 2

Actual behavior:

array length only allow 2

Playground Link:

Related Issues:

Question

Most helpful comment

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

declare function abc(data: ArrayTwoOrMore<string>)

abc([]) // got expected error
abc(["a"]) // got expected error 
abc(["a", "b"]) // no error
abc(["a", "b", "c"]) // no error

Playground link

Edit: Converted to stackoverflow question since I didn't notice any already existing: https://stackoverflow.com/questions/49910889/typescript-array-with-minimum-length

All 5 comments

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

declare function abc(data: ArrayTwoOrMore<string>)

abc([]) // got expected error
abc(["a"]) // got expected error 
abc(["a", "b"]) // no error
abc(["a", "b", "c"]) // no error

Playground link

Edit: Converted to stackoverflow question since I didn't notice any already existing: https://stackoverflow.com/questions/49910889/typescript-array-with-minimum-length

@kpdonn thx

@kpdonn hmm

there has something happen when i use ...argv

console.log(abc([str, n, s])); // => no error
console.log(abc([str, n, s, ...argv])); // => error

2018-04-21-00-04-46-1

@bluelovers It looks like spreading argv causes it to see the entire expression as just string[] and lose the information about the earlier indices. It might be worth opening a new issue specifically about that case since it might be considered a bug. Seems like one to me anyway.

Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Antony-Jones picture Antony-Jones  路  3Comments

Zlatkovsky picture Zlatkovsky  路  3Comments

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

wmaurer picture wmaurer  路  3Comments