How to clear a typed array in typescript and preserving its type?
This post seems to be out of date. There is a new way to do this.
this.array = [] as CustomType[];
The type information is determined by the type annotation on the field (exampleArray: CustomType[]
). At runtime Javascript arrays are untyped anyway. 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
. 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):
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 {}