Javascript 如何在 Typescript 中创建一个空字符串数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32738387/
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-08-23 14:09:21  来源:igfitidea点击:

How can I make an empty string array in Typescript?

javascripttypescript

提问by

I would like to have an array that holds string error messages. Here's the code that I came up with:

我想要一个包含字符串错误消息的数组。这是我想出的代码:

var errors: [string];
errors = [];
Object.keys(response.data.modelState).forEach(function (key) {
    errors.push.apply(errors, response.data.modelState[key]);
});

I tried some different ways to add a typescript definition to the variable errors but none seem to work for this case. The first definition works okay but then when I am pushing values I need to push to an array and when I set:

我尝试了一些不同的方法来向变量错误添加打字稿定义,但似乎没有一种方法适用于这种情况。第一个定义工作正常,但是当我推送值时,我需要推送到一个数组,当我设置时:

errors = []; 

Then it gives me an error message:

然后它给了我一条错误消息:

Severity Code Description Project File Line Error TS2322 Type 'undefined[]' is not assignable to type '[string]'. Property '0' is missing in type 'undefined[]'. Severity Code Description Project File Line Error Build: Type 'undefined[]' is not assignable to type '[string]'.

严重性代码描述项目文件行错误 TS2322 类型“undefined[]”不可分配给类型“[string]”。类型“undefined[]”中缺少属性“0”。严重性代码描述项目文件行错误构建:类型“undefined[]”不可分配给类型“[string]”。

采纳答案by Radim K?hler

The definition of string arrayshould be:

字符串数组的定义应该是:

// instead of this
// var errors: [string];
// we need this
var errors: string[];
errors = [];

Note:another issue could be the parameter key here

注意:另一个问题可能是这里的参数键

...forEach(function (key) {...

I would guess that we often should declare two of them, because first is very often value, second key/index

我猜我们经常应该声明其中的两个,因为第一个通常是值,第二个是键/索引

Object.keys(response.data.modelState)
      .forEach(function (value, key) {
    errors.push.apply(errors, response.data.modelState[key]);
});

And even, we should use arrow function, to get the parent as this

甚至,我们应该使用箭头函数,将父级作为 this

Object.keys(response.data.modelState)
      .forEach( (value, key) => {
    errors.push.apply(errors, response.data.modelState[key]);
});

回答by Gero

Outside of a method:

在方法之外:

arr: string[] = [];

回答by Anders Zommarin

An alternative is to set the lengthto 0:

另一种方法是将 设置length0

const myArray = [1, 2, 3, 4]
myArray.length = 0

This makes it possible to use constin contexts where emptying the array is needed.

这使得可以const在需要清空数组的上下文中使用。

回答by wvdz

Missing an obvious answer, needed when not assigning it to a variable: [] as string[]

缺少一个明显的答案,在不将其分配给变量时需要: [] as string[]