Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何清除typescript中的类型化数组并保留其类型?_Javascript_Angular_Typescript - Fatal编程技术网

Javascript 如何清除typescript中的类型化数组并保留其类型?

Javascript 如何清除typescript中的类型化数组并保留其类型?,javascript,angular,typescript,Javascript,Angular,Typescript,现在在一个类中,我声明了一个类型为CustomType的数组,如下所示 class Example { public exampleArray: CustomType[]; public clearArray() { this.exampleArray = []; } } 正如您所见,clearArray分配了一个未定义的空数组类型,这似乎丢失了类型信息 如何清除数组但保留其声明的类型?类型信息由字段上的类型注释决定(exampleArray:CustomType[])。运

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

class Example {
  public exampleArray: CustomType[];
  public clearArray() {
    this.exampleArray = [];
  }
}
正如您所见,clearArray分配了一个未定义的空数组类型,这似乎丢失了类型信息


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

类型信息由字段上的类型注释决定(
exampleArray:CustomType[]
)。运行时Javascript数组无论如何都是非类型化的。编译器将允许将空数组(
[]
)分配给任何被认为是安全的对象,因为其中没有对象,所以它可以是
自定义类型的数组。然后,字段类型将阻止您推送到任何其他类型的数组对象:

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`
    }
}
注意

如果这是一个没有类型注释的变量,则该变量将被推断为
any[]
,这可能会导致问题(无论是在分配数组文字时还是在推送到数组时,类型都不会被选中):

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

let noAnnotationArray = [] //  any[]
let withAnnotation:CustomType[] = [{}] //  error
let withAssertion = <CustomType[]>[{}] // no error even though we assign {}
let-withAnnotation:CustomType[]=[{}]//错误
let withAssertion=[{}]//即使我们分配了{},也没有错误
您可以尝试使用

this.exampleArray = <CustomType[]>[];
this.exampleArray=[];

清空数组的方法有三种

  • 将其长度设置为0

    myArr.length=0

  • 使用拼接法阵列

    myArr.拼接(0,myArr.长度)

  • Pop()数组的每个元素

    while(myArr.length){
      myArr.pop();
    }    
    
  • 您始终可以通过更改长度来清除列表项 属性设置为0

    例如:
    this.exampleArray.length=0


    将length设置为0将清除数组中的所有元素,而不更改数组的引用。

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

    this.array = [] as CustomType[];
    

    即使通过以下方法作为参数传递,也要清理数组:

    myArray.length = 0;
    

    exampleArray.length=0可以吗?它在JS中工作,不确定TS是否接受它。类型信息首先不会丢失。你的实际问题是什么?这听起来像一个XY问题。可能是@LW001的副本,但实际上不是副本。。OP担心当您将非类型化的空数组分配给字段(该字段不是且是类型安全的)时,类型安全性会丢失@TitianCernicova Dragomir抱歉,只是单击一次错误它将是[],但您得到了什么?没什么。为什么要使用类型断言?数组的类型已由
    数组
    上的注释确定。
    as
    相当于
    let with assertion=[{}]
    ,我解释了为什么在anks@Luke Becker中是一个坏主意。上面的评论是错误的,因为您作为新数组传递的[]实例的as是正确的,所以谢谢!。