简体   繁体   English

Typescript:定义数组<t> object 内部</t>

[英]Typescript: Define array of <T> inside object

I'm coming from a JS background, and I'm learning TS.我来自JS背景,并且正在学习TS。

I want to define an object with a single field, which is an array of strings, while taking advantage of strong typing.我想用一个字段定义一个 object,它是一个字符串数组,同时利用强类型。

let wrapper = {
  things: ['Thing 1']
}

wrapper.things[0] = 3; // wrong

Now, this works (and by works I mean it results in an error) because you can't assign a number to what has been inferred as an array of strings.现在,这行得通(我的意思是它会导致错误),因为您无法将数字分配给已推断为字符串数组的内容。 What if I didn't want to provide an initial value to things , though?但是,如果我不想为things提供初始值怎么办? Something like this:像这样的东西:

let wrapper = {
  things<String>: []
}

wrapper.things.push(3) // wrong
wrapper.things.push('abc') // correct

You can define a type.您可以定义一个类型。

interface Wrapper {
    things: string[];
}

const wrapper: Wrapper = { things: [] };

Or, if it isn't particularly reusable, inline it:或者,如果它不是特别可重用,则内联它:

const wrapper: { things: string[] } = { things: [] };

I think you just have the order a little off.我想你只是把订单少了一点。 Try this:尝试这个:

const wrapper = {
  things: [] as string[]
};

or use an interface (probably more recommended) via the other answer.或通过其他答案使用界面(可能更推荐)。

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

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