typescript 如何定义对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35435042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:54:05  来源:igfitidea点击:

How can I define an array of objects?

typescript

提问by John Weisz

I am creating an array of objects in TypeScript:

我在 TypeScript 中创建了一个对象数组:

 userTestStatus xxxx = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
 };

Can someone tell me how I could declare its type correctly? Is it possible to do inline or would I need two definitions?

有人能告诉我如何正确声明它的类型吗?是否可以内联或者我需要两个定义?

I'm looking to replace the xxxwith a type declaration, so that later on TypeScript would alert me if I used something like userTestStatus[3].nammmeby mistake.

我希望xxx用类型声明替换,以便稍后如果我userTestStatus[3].nammme错误地使用了类似的东西,TypeScript 会提醒我。

回答by John Weisz

You are better off using a native arrayinstead of an object literal with number-like properties, so that numbering (as well as numerous other array functions) are taken care of off-the-shelf.

最好使用本机数组而不是具有类似数字属性的对象字面量,这样编号(以及许多其他数组函数)都可以现成。

What you are looking for here is an inline interfacedefinition for your array that defines every element in that array, whether initially present or introduced later:

您在此处寻找的是数组的内联接口定义,该定义定义了该数组中的每个元素,无论是最初存在还是稍后引入:

let userTestStatus: { id: number, name: string }[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

If you are initializing your array with values right away, the explicit type definition is not a necessity; TypeScript can automatically infer most element types from the initial assignment:

如果您立即使用值初始化数组,则不需要显式类型定义;TypeScript 可以从初始赋值中自动推断出大多数元素类型:

let userTestStatus = [
    { "id": 0, "name": "Available" },
    ...
];

userTestStatus[34978].nammme; // Error: Property 'nammme' does not exist on type [...]

回答by Brocco

What you have above is an object, not an array.

你上面有的是一个对象,而不是一个数组。

To make an array use [& ]to surround your objects.

要制作数组,请使用[&]围绕您的对象。

userTestStatus = [
  { "id": 0, "name": "Available" },
  { "id": 1, "name": "Ready" },
  { "id": 2, "name": "Started" }
];

Aside from that TypeScript is a superset of JavaScript so whatever is valid JavaScript will be valid TypeScript so no other changes are needed.

除此之外,TypeScript 是 JavaScript 的超集,因此任何有效的 JavaScript 都是有效的 TypeScript,因此不需要其他更改。

Feedback clarification from OP... in need of a definition for the model posted

来自 OP 的反馈澄清...需要对发布的模型进行定义

You can use the types defined here to represent your object model:

您可以使用此处定义的类型来表示您的对象模型:

type MyType = {
    id: number;
    name: string;
}

type MyGroupType = {
    [key:string]: MyType;
}

var obj: MyGroupType = {
    "0": { "id": 0, "name": "Available" },
    "1": { "id": 1, "name": "Ready" },
    "2": { "id": 2, "name": "Started" }
};
// or if you make it an array
var arr: MyType[] = [
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
];

回答by Ogglas

Some tslintrules are disabling use of [], example message: Array type using 'T[]' is forbidden for non-simple types. Use 'Array<T>' instead.

一些tslint规则禁止使用 [],示例消息:Array type using 'T[]' is forbidden for non-simple types. Use 'Array<T>' instead.

Then you would write it like:

然后你会这样写:

var userTestStatus: Array<{ id: number, name: string }> = Array(
    { "id": 0, "name": "Available" },
    { "id": 1, "name": "Ready" },
    { "id": 2, "name": "Started" }
);

回答by bakkal

What you really want may simply be an enumeration

你真正想要的可能只是一个枚举

If you're looking for something that behaves like an enumeration (because I see you are defining an object and attaching a sequential ID 0, 1, 2 and contains a name field that you don't want to misspell (e.g. name vs naaame), you're better off defining an enumeration because the sequential ID is taken care of automatically, and provides type verification for you out of the box.

如果您正在寻找行为类似于枚举的内容(因为我看到您正在定义一个对象并附加一个顺序 ID 0、1、2 并包含一个您不想拼错的名称字段(例如名称与 naaame) ,你最好定义一个枚举,因为顺序 ID 是自动处理的,并为你提供开箱即用的类型验证。

enum TestStatus {
    Available,     // 0
    Ready,         // 1
    Started,       // 2
}

class Test {
    status: TestStatus
}

var test = new Test();
test.status = TestStatus.Available; // type and spelling is checked for you,
                                    // and the sequence ID is automatic

The values above will be automatically mapped, e.g. "0" for "Available", and you can access them using TestStatus.Available. And Typescript will enforce the type when you pass those around.

上面的值将自动映射,例如“0”代表“可用”,您可以使用TestStatus.Available. 当您传递这些类型时,Typescript 将强制执行该类型。

If you insist on defining a new type as an array of your custom type

如果您坚持将新类型定义为自定义类型的数组

You wanted an arrayof objects, (not exactly an object with keys "0", "1" and "2"), so let's define the type of the object, first, then a type of a containing array.

您需要一个对象数组(不完全是具有键“0”、“1”和“2”的对象),因此让我们首先定义对象的类型,然后定义包含数组的类型。

class TestStatus {
    id: number
    name: string

    constructor(id, name){
        this.id = id;
        this.name = name;
    }
}

type Statuses = Array<TestStatus>;

var statuses: Statuses = [
    new TestStatus(0, "Available"),
    new TestStatus(1, "Ready"),
    new TestStatus(2, "Started")
]

回答by Akash Singh

You can also try

你也可以试试

    interface IData{
        id: number;
        name:string;
    }

    let userTestStatus:Record<string,IData> = {
        "0": { "id": 0, "name": "Available" },
        "1": { "id": 1, "name": "Ready" },
        "2": { "id": 2, "name": "Started" }
    };

To check how record works: https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

要检查记录如何工作:https: //www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Here in our case Record is used to declare an object whose key will be a string and whose value will be of type IData so now it will provide us intellisense when we will try to access its property and will throw type error in case we will try something like userTestStatus[0].nameee

在我们的例子中,Record 用于声明一个对象,其键将是一个字符串,其值将是 IData 类型,所以现在它将为我们提供智能感知,当我们尝试访问其属性时,将抛出类型错误,以防我们尝试类似于 userTestStatus[0].nameee