1

I have this javascript object:

subjects = {
    "1": { "id": 1, "name": "City" },
    "100": { "id": 100, "name": "Test" }
};

Can someone help me by telling me how I could define this in typescript. I know I can use "any" but I would like to do this properly

2 Answers 2

1

If you're looking to be able to iterate over the array using a for loop, you'd need to define length as well.

Then in theory you could define it as subjects : { id: number; name: string; }[] = <...>

If you don't want to iterate over it, then you could just define it as subjects : { [key: string] : { id: number; name: string; } } = <...>

Sign up to request clarification or add additional context in comments.

1 Comment

- Thanks. Actually I want to iterate over it with a forEach. I have another question on that. Maybe you could have a quick look and then perhaps I can accept both answers if you can see what is wrong. Thanks
1
subjects list:number[] = [1, 2, 3];

or

subjects list:Array<number> = [1, 2, 3];

2 Comments

Is there a way that I could also define the contents of my object such as the id and name? Thanks
Inside the array you ask?

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.