The determination of type information relies on the field's type annotation (e.g., exampleArray: CustomType[]
). Even though Javascript arrays are untyped at runtime, the compiler permits assigning an empty array ([]
) to any variable as a safety measure. This is because, with no objects inside, it can be assumed to be an array of CustomType
. Consequently, trying to push objects of a different type into the array will result in a compilation error due to the declared field 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 the variable had no type annotation, it would default to any[]
, which could lead to issues since type checking is not enforced when assigning or pushing elements to the array:
let noAnnotationArray = [] // any[]
In such cases, adding a type annotation is strongly recommended for ensuring type safety. Using type assertions (as proposed in other responses) might introduce unnoticed errors if non-matching items are added to the array later on:
let withAnnotation:CustomType[] = [{}] // error
let withAssertion = <CustomType[]>[{}] // no error even though we assign {}