Monday, January 20, 2025
HomeProgrammingHow do you declare and initialize a dictionary in TypeScript?

How do you declare and initialize a dictionary in TypeScript?

In TypeScript, a dictionary can be declared and initialized using an object or the Record utility type. Here’s how to do both:

1. Using an Object:

let dictionary: { [key: string]: number } = {};
dictionary[“age”] = 25;
dictionary[“year”] = 2025;

See also  What is Loops in Python?

2. Using the Record Type:

let dictionary: Record = {
age: 25,
year: 2025
};

Both methods create a dictionary where the keys are strings and the values are numbers. The Record type is preferred for type safety and better readability.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x