Typescript tuple error: Target requires 3 element(s) but source may have fewer

Viewed 5514

I got simple TS tuple

const argTuple: {key1: string, key2: string, key3:string}[] = [
                {key: "key", key2: "key1", key3: "3"},
                {key: "key", key2: "key2", key3: "3"}
            ]

const arg:[string, string, string] = Object.values(argTuple)

but arg got error: Target requires 3 element(s) but source may have fewer.ts(2322) I don't understand why tuple could have less element in TS.

1 Answers

Looks like you got confused with the syntax here.

The following means "an array with exactly three string elements" (yes, the key1, key2, and key3 parts are just labels, they are completely irrelevant to typing information):

[key1: string, key2: string, key3:string]

You probably want an array of objects with key1, key2, and key3 properties, which is:

{ key1: string, key2: string, key3:string }[]

… or (equivalently):

Array<{ key1: string, key2: string, key3:string }>
Related