[英]Typescript - Type a function that accepts an array, alters one of its properties, but still returns the same typed array
[英]How to clear a typed array in typescript and preserving its type?
現在在一個類中,我聲明了一個類型為:CustomType 的數組,如下所示
class Example {
public exampleArray: CustomType[];
public clearArray() {
this.exampleArray = [];
}
}
如您所見, clearArray 分配了一個空數組的 UNDEFINED 類型,這似乎丟失了類型信息。
如何清除數組但保留其聲明的類型?
類型信息由字段上的類型注釋決定( 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`
}
}
筆記
如果這是一個沒有類型注釋的變量,則該變量將被推斷為any[]
,這可能會導致問題(在分配數組文字或推送到數組時不會檢查類型):
let noAnnotationArray = [] // any[]
在這種情況下,添加類型注釋仍然是最好的方法。 如果稍后有人將項目添加到數組中,則類型斷言(如其他答案中所建議的)可能會導致未捕獲的錯誤:
let withAnnotation:CustomType[] = [{}] // error
let withAssertion = <CustomType[]>[{}] // no error even though we assign {}
這個帖子似乎已經過時了。 有一種新方法可以做到這一點。
this.array = [] as CustomType[];
您始終可以通過將 length 屬性更改為 0 來清除列表項
例如: this.exampleArray.length = 0
將 length 設置為 0 會清除數組中的所有元素,而不會更改數組的引用。
清空數組有3種方式
設置其長度 = 0
myArr.length = 0;
使用拼接方法數組
myArr.splice(0,myArr.length);
Pop() 數組的每個元素
while(myArr.length){ myArr.pop(); }
你可以試試
this.exampleArray = <CustomType[]>[];
即使通過方法作為參數傳遞,也要清理數組:
myArray.length = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.