Type definition for array with objects in TypeScript
12,339
Solution 1
If you want to define an object which property names are not known at compile time and which values are numbers, you should use an "index signature" (Thanks @Joe Clay):
interface MyObject {
[propName: string]: number;
}
Then you can write:
export const AlternativeSpatialReferences: MyObject[] = [
{
'25833': 25833
},
{
'25832': 25832
},
{
'25831': 25831
},
{
'Google': 4326
}
];
Solution 2
in typescript you make use of any
type ,
any used for - need to describe the type of variables that we do not know when we are writing an application.
Array<any>
if you want to go for some strong type than you should create new class with two property
public class KeyValue
{
key:string;
value:number;
}
let myarray: KeyValue[] = new Array<KeyValue>();
myarray.push({key: '25833' , value : 25833});
myarray.push({key: 'Google' , value : 123});
and convert your current array values in strong type.
Author by
podeig
Updated on June 05, 2022Comments
-
podeig almost 2 years
How can be defined types in TypeScript for en such array:
export const AlternativeSpatialReferences: Array< ??? > = [ { '25833': 25833 }, { '25832': 25832 }, { '25831': 25831 }, { 'Google': 4326 } ];
Now I just use Array<{}>, but want define properly.
-
indexoutofbounds over 6 yearsWhy any, those are obviously objects.
Array<object>
would be more appropriate here, imho! -
Joe Clay over 6 yearsIn case people reading this answer want to find further info - this syntax is called an 'index signature'.
-
klugjo over 6 years@JoeClay Thanks, I didnt know that. updated my answer with the information