Horje
Typescript Dictionary

In TypeScript, a dictionary typically refers to an object where the keys are of a consistent type (often strings or numbers) and the values can be of any type. As the dictionary is not supported by TpeScript natively. It’s similar to a hash map or associative array in other programming languages. Dictionaries allow you to store and retrieve data using keys, providing a flexible way to manage collections of data in TypeScript programs.

Prerequisites

Steps to Implement Typescript Dictionary

Step 1: Initialize the Project

Create a new directory for your project and navigate into it:

mkdir typescript-dictionary-project
cd typescript-dictionary-project

Step 2: Initialize a new Node.js project:

npm init -y

Step 3: Install TypeScript

Install TypeScript as a dev dependency:

npm install typescript --save-dev

Folder Structure:

kjh

Dependencies:

"devDependencies": {
"typescript": "^5.5.3"
}

Step 4: Configure TypeScript

Create a tsconfig.json file in the project root with the following content:

{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src"]
}

Step 5: Write TypeScript Code

The code defines a generic Dictionary<T> interface where keys are strings and values can be of any type T. It creates a Dictionary<number> instance, adds entries dynamically using a function addEntry, and outputs the updated dictionary with added key-value pairs.

Example: This example shows the creation of Dictionary using TypeScript.

JavaScript
// index.ts

interface Dictionary<T> {
    [key: string]: T;
}

const dictionary: Dictionary<number> = {
    "one": 1,
    "two": 2,
    "three": 3
};

const addEntry = (dict: Dictionary<number>,
    key: string, value: number): void => {
    dict[key] = value;
};

addEntry(dictionary, "four", 4);

console.log(dictionary);

Step 6: Compile and Run the Code

Compile the TypeScript code to JavaScript:

npx tsc

Run the generated JavaScript code:

node src/index.js

Output:

{
"one": 1,
"two": 2,
"three": 3,
"four": 4
}



Reffered: https://www.geeksforgeeks.org


TypeScript

Related
Typescript keyof Typescript keyof
Dynamic Import Expressions in TypeScript Dynamic Import Expressions in TypeScript
Typescript Set Typescript Set
How to Test TypeScript with Jest? How to Test TypeScript with Jest?
Error Handling with the Either type in TypeScript Error Handling with the Either type in TypeScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
23