Source has N elements but target allows only 1 in TS

avatar

Borislav Hadzhiev

Last updated: Mar 1, 2022

banner

Photo from Unsplash

Source has N elements but target allows only 1 in TS #

The error "Source has N element(s) but target allows only 1" occurs when we declare a tuple instead of an array. To solve the error change the variable's type to Type[] instead of [Type] or adjust the length of the tuple.

Here is an example of how the error occurs.

index.ts
// ⛔️ Error: Source has N element(s) // but target allows only 1 const arr: [number] = [1, 2, 3];

We declared a tuple that has a single element of type number, but tried to add 3 elements to it and got the error.

To solve this, declare an array instead of a tuple.

index.ts
const arr: number[] = [1, 2, 3];

The line above declares an array of numbers and not a tuple containing a single number.

The difference being - [Type] is a tuple containing a single element of type Type, and Type[] is an array containing elements of type Type.

The tuple type is used to express an array with fixed number of elements whose types are known, but can be different.

If you need to declare a two-dimensional array, use the Type[][] syntax.

index.ts
const arr: number[][] = [ [1, 2, 3], [3, 4, 5], ];

Here is an example of how you would declare an array of objects.

index.ts
const arr: { name: string; age: number }[] = [ { name: 'Alice', age: 27 }, { name: 'Bob', age: 28 }, ];

If your variable declaration gets busy, use a type alias.

index.ts
type Employee = { id: number; name: string; salary: number; }; const arr: Employee[] = [ { id: 1, name: 'Alice', salary: 100, }, { id: 2, name: 'Bob', salary: 200, }, ];

The code snippet above declares an array of objects with type Employee.

Conclusion #

The error "Source has N element(s) but target allows only 1" occurs when we declare a tuple instead of an array. To solve the error change the variable's type to Type[] instead of [Type] or adjust the length of the tuple.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.