[英]How to clear a typed array in typescript and preserving its type?
Now in a class, I declared an array with type: CustomType, like below现在在一个类中,我声明了一个类型为:CustomType 的数组,如下所示
class Example {
public exampleArray: CustomType[];
public clearArray() {
this.exampleArray = [];
}
}
As you can see the clearArray assign an UNDEFINED type of an empty array, which seems lost the type information.如您所见, clearArray 分配了一个空数组的 UNDEFINED 类型,这似乎丢失了类型信息。
How I can clear the array but preserving its declared type?如何清除数组但保留其声明的类型?
The type information is determined by the type annotation on the field ( exampleArray: CustomType[]
).类型信息由字段上的类型注释决定( exampleArray: CustomType[]
)。 At runtime Javascript arrays are untyped anyway.在运行时 Javascript 数组无论如何都是无类型的。 The compiler will allow an empty array ( []
) to be assigned to anything as this is considered safe, since there are no objects inside, it can be an array of CustomType
.编译器将允许将空数组 ( []
) 分配给任何东西,因为这被认为是安全的,因为内部没有对象,它可以是CustomType
数组。 The field type will then prevent you form pushing to the array objects of any other type:然后,字段类型将阻止您将表单推送到任何其他类型的数组对象:
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`
}
}
Note笔记
If this had been a variable with no type annotation, the variable would have been inferred to any[]
, which can lead to problems (types are not checked on either when assigning an array literal or when you would push to the array):如果这是一个没有类型注释的变量,则该变量将被推断为any[]
,这可能会导致问题(在分配数组文字或推送到数组时不会检查类型):
let noAnnotationArray = [] // any[]
In this case, adding a type annotation is still the best way to go.在这种情况下,添加类型注释仍然是最好的方法。 Type assertions (as suggested in other answers) can lead to uncaught errors if later someone adds an item to the array:如果稍后有人将项目添加到数组中,则类型断言(如其他答案中所建议的)可能会导致未捕获的错误:
let withAnnotation:CustomType[] = [{}] // error
let withAssertion = <CustomType[]>[{}] // no error even though we assign {}
This post seems to be out of date.这个帖子似乎已经过时了。 There is a new way to do this.有一种新方法可以做到这一点。
this.array = [] as CustomType[];
You can always clear the list items by changing the length property to 0您始终可以通过将 length 属性更改为 0 来清除列表项
eg: this.exampleArray.length = 0
例如: this.exampleArray.length = 0
Setting length to 0 clears all the elements in the array without altering the reference of the array.将 length 设置为 0 会清除数组中的所有元素,而不会更改数组的引用。
There can be 3 ways of emptying an array清空数组有3种方式
setting its length = 0设置其长度 = 0
myArr.length = 0;
using splice method Array使用拼接方法数组
myArr.splice(0,myArr.length);
Pop() each element of array Pop() 数组的每个元素
while(myArr.length){ myArr.pop(); }
你可以试试
this.exampleArray = <CustomType[]>[];
即使通过方法作为参数传递,也要清理数组:
myArray.length = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.