3

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.

2 Answers 2

8

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
    } 
];
Sign up to request clarification or add additional context in comments.

2 Comments

In case people reading this answer want to find further info - this syntax is called an 'index signature'.
@JoeClay Thanks, I didnt know that. updated my answer with the information
5

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.

2 Comments

Why any, those are obviously objects. Array<object> would be more appropriate here, imho!
I needed Array<any> as stated in the answer as opposed to @indexoutofbounds comment because object resulted in foo does not exist on {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.