简体   繁体   English

在 object 中指定数组类型(打字稿)

[英]specify type of array in an object (typescript)

I know how to declare the type in a variable.我知道如何在变量中声明类型。

let members: string[] = []    // this works perfectly

I want to have an array of strings in an object.我想在 object 中有一个字符串数组。 How can I format it correctly?如何正确格式化?

const team = {
   name: String,
   members<string[]>: [],   // this gives error!!
}

The solution解决方案

const team = {
   name: String,
   members: [] as string[]
}

One way is to specify the type of the whole object, just like you're doing with members - put the type of the object after a colon, before the = assignment:一种方法是指定整个 object 的类型,就像您对members所做的那样 - 将 object 的类型放在冒号之后,在=分配之前:

const team: {
  name: StringConstructor;
  members: string[];
} = {
  name: String,
  members: [],
};

Another way is to assert the type of only the property in question with as (but I don't like this approach because I prefer to only use as to indicate to TypeScript something that there's no way of annotating otherwise).另一种方法是只用as断言有问题的属性的类型(但我不喜欢这种方法,因为我更喜欢只使用as向 TypeScript 指示无法以其他方式注释的东西)。

const team = {
  name: String,
  members: [] as string[],
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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