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

14 javascript typescript

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

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

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

errors = []; 
Run Code Online (Sandbox Code Playgroud)

然后它给我一个错误信息:

严重级代码说明项目文件行错误TS2322类型'undefined []'不能分配给'[string]'类型.'undefined []'类型中缺少属性'0'.严重级代码描述项目文件行错误构建:类型'undefined []'不能分配给'[string]'类型.

Rad*_*ler 16

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

// instead of this
// var errors: [string];
// we need this
var errors: string[];
errors = [];
Run Code Online (Sandbox Code Playgroud)

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

...forEach(function (key) {...
Run Code Online (Sandbox Code Playgroud)

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

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

甚至,我们应该使用箭头功能,以获得父母 this

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


Ger*_*ero 13

在方法之外:

arr: string[] = [];
Run Code Online (Sandbox Code Playgroud)


wvd*_*vdz 8

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