简体   繁体   中英

Cannot push object with typed fields to array (Typescript error)

New to Typescript and got stuck on a basic problem. I would like to push objects to an array like so:

type SomeArray = [
    {
      id: string;
    }
];

const someArray: SomeArray = [];

The first problem is that it does not allow me to initialize with an empty array. Do I really need a union for this? ie SomeArray = [...] | [] SomeArray = [...] | [] ?

Next problem is that I can't push items to it :

type SomeArray = [
    {
      id: string;
    }
] | [];

const someArray: SomeArray = [];

someArray.push({ id: 'a' })

Type 'string' is not assignable to type 'never'.(2322)

What is the correct way to define an array that accepts a typed object?

You've defined SomeArray as a tuple , not an array. A tuple is a way to specify not only that it's an array, but exactly how many elements it will have, and the types on each index (with different indices possibly having different types). So in your case, you've specified that the array will only ever have exactly one element in it, which makes empty arrays and pushing to the array illegal.

If you want an array with 0 or more elements, you need to put the square brackets after , as in:

type SomeArray = { id: string }[];

I've just started using TypeScript and encountered this same problem. I had the additional problem where the properties I would add needed to be defined dynamically after the initialisation of the object.

I found that the following syntax works well for pushing to objects in TypeScript:

 let someArray = any[] = [] someArray.push({id: "a",anotherProperty: "b"}) someArray.push({aThirdThing:"b"})

The great thing about this method is that you don't have to anticipate all your properties when you define the array, you can do it on the fly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM