[英]Cannot push object with typed fields to array (Typescript error)
New to Typescript and got stuck on a basic problem. Typescript 的新手,遇到了一个基本问题。 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 = [...] | []
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)
类型“字符串”不可分配给类型“从不”。(2322)
What is the correct way to define an array that accepts a typed object?定义接受类型化 object 的数组的正确方法是什么?
You've defined SomeArray as a tuple , not an array.您已将 SomeArray 定义为tuple ,而不是数组。 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:如果您想要一个包含 0 个或更多元素的数组,则需要将方括号放在之后,如下所示:
type SomeArray = { id: string }[];
I've just started using TypeScript and encountered this same problem.我刚刚开始使用 TypeScript 并遇到了同样的问题。 I had the additional problem where the properties I would add needed to be defined dynamically after the initialisation of the object.
我有一个额外的问题,我要添加的属性需要在 object 初始化之后动态定义。
I found that the following syntax works well for pushing to objects in TypeScript:我发现以下语法适用于推送到 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.这种方法的好处是您不必在定义数组时预测所有属性,您可以即时完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.