如何清除打字稿中的类型数组并保留其类型?

Vin*_*-cm 5 javascript typescript angular

现在在一个类中,我声明了一个类型为:CustomType的数组,如下所示

class Example {
  public exampleArray: CustomType[];
  public clearArray() {
    this.exampleArray = [];
  }
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,clearArray指定了一个空数组的UNDEFINED类型,这似乎丢失了类型信息.

我如何清除数组但保留其声明的类型?

Tit*_*mir 9

类型信息由字段(exampleArray: CustomType[])上的类型注释确定.在运行时,Javascript数组无论如何都是无类型的.编译器将允许将空数组([])分配给任何东西,因为这被认为是安全的,因为里面没有对象,它可以是一个数组CustomType.然后,字段类型将阻止您形成推送到任何其他类型的数组对象:

class CustomType { x: number}
class Example {
    public exampleArray: CustomType[];
    public clearArray() {
        this.exampleArray = [];
        this.exampleArray.push(new CustomType())
        this.exampleArray.push({}) // error not a `CustomType`
    }
}
Run Code Online (Sandbox Code Playgroud)

注意

如果这是一个没有类型注释的变量,那么该变量就会被推断出来any[],这会导致出现问题(在分配数组文字或推送到数组时不会检查类型):

let noAnnotationArray = [] //  any[]
Run Code Online (Sandbox Code Playgroud)

在这种情况下,添加类型注释仍然是最好的方法.如果以后有人将一个项添加到数组中,则类型断言(如其他答案中所建议的)可能导致未被捕获的错误:

let withAnnotation:CustomType[] = [{}] //  error
let withAssertion = <CustomType[]>[{}] // no error even though we assign {}
Run Code Online (Sandbox Code Playgroud)


Luk*_*ker 7

这个帖子似乎已经过时了。有一种新方法可以做到这一点。

this.array = [] as CustomType[];
Run Code Online (Sandbox Code Playgroud)