Reputation: 84
I define an array of a specific type in typescript. When assigning values that do not correspond to the type, error messages are generated as required. An assignment of the type any works, even if the type is not correct.
Do I misunderstand the type definition of an array? Or do I underestimate the "power" of the anys :-)
Here is a brief example:
export class ItemList {
items: Array<string> = [];
constructor() {
// push a string directly => works
this.items.push('item 1');
// push a string variable => works
let item2:string = 'item 2';
this.items.push(item2);
// push a number variable => doesn't work
let item3 = 3;
this.items.push(item3);
// push a number as any type => works
let item4:any = 4;
this.items.push(item4);
}
}
let itemList = new ItemList();
The error from the tsc is:
error TS2345: Argument of type 'number' is not assignable to parameter of type
'string'.
Funny thing: the plunkers here works.
Upvotes: 5
Views: 21667
Reputation: 1562
do I underestimate the "power" of the anys
Yes.
any
is assignable to any type, so even though items
is string[]
and items.push()
accepts only string
, any
is accepted.
But in the end I do not have the result that I expect.
Disallow any
then. There are a noImplicitAny
rule for tsconfig
and no-any
and no-unsafe-any
rules for tslint
.
Still, as seen in @artem's example, since TypeScript does not control co- and contravariance of function parameters, its type system can't guarantee the desired type safety.
Upvotes: 0
Reputation: 3645
Array of specific type in typescript
export class RegisterFormComponent
{
genders = new Array<GenderType>();
loadGenders()
{
this.genders.push({name: "Male",isoCode: 1});
this.genders.push({name: "FeMale",isoCode: 2});
}
}
type GenderType = { name: string, isoCode: number }; // Specified format
Array of any type in typescript
export class RegisterFormComponent
{
genders = new Array<any>();
}
Upvotes: 2
Reputation: 801
What you are looking for is union types.
Try this
items: (string|number)[]; // or...
items: Array<string|number>;
Or you can initialize it like this
items: (string|number)[] = ["Hello", 154]; // or...
items: Array<string|number> = ["Hello", 154];
Upvotes: 17