Open In App

How to get Value from a Dictionary in Typescript ?

In TypeScript, a dictionary consists of objects that store data in the key-value pairs, and allow retrieval of values based on the specified keys.

We can get value from a dictionary for the specific keys using various approaches.

Using Dot Notation

In this approach, we will use the dot notation to directly access the value associated with a key in the dictionary and print the resulting and retrieved value in the console.

Syntax:

const value = obj.propertyName;

Example: The below example uses dot notation to get value from a dictionary in TypeScript.

interface obj {
    name: string;
    desc: string;
    est: number;
}
const dict: obj = {
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
    est: 2009,
};
const res: string = dict.name;
console.log(
    dict.name, ",", dict.desc,
    ", was establised in: ", dict.est
);

Output:

GeeksforGeeks, A Computer Science Portal, was establised in: 2009

Using Bracket Notation

In this approach, we use bracket notation to access the value associated with the key in the dictionary object. The retrieved value is logged to the console using console.log().

Syntax:

const value = obj['propertyName'];

Example: The below example uses bracket notation to get value from a dictionary in TypeScript.

type obj = {
    name: string;
    desc: string;
    est: number;
};
const dict: obj = {
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
    est: 2009,
};
const res: string = dict.name;
console.log(
    dict.name, ",", dict.desc,
    ", was establised in: ", dict.est
);

Output:

GeeksforGeeks, A Computer Science Portal, was establised in: 2009

Using a Function

The function approach involves creating a reusable function that takes a dictionary object and a key as parameters, returning the corresponding value. This method ensures code modularity and flexibility, allowing easy retrieval of values from dictionaries in TypeScript.

Syntax

const getValue = <T extends Record<string, any>>(
dictionary: T,
key: keyof T
): T[keyof T] | undefined => {
return dictionary[key];
};

Example

const getValue = <T extends Record<string, any>>(
    dictionary: T,
    key: keyof T
): T[keyof T] | undefined => {
    return dictionary[key];
};

// Define the interface
interface obj {
    name: string;
    desc: string;
    est: number;
}

// Define the dictionary object
const dict: obj = {
    name: "GeeksforGeeks",
    desc: "A Computer Science Portal",
    est: 2009,
};

// Usage
console.log("Name:", getValue(dict, 'name'));
console.log("Description:", getValue(dict, 'desc'));
console.log("Established Year:", getValue(dict, 'est')?.toString());

Output:

Name: GeeksforGeeks
Description: A Computer Science Portal
Established Year: 2009
Article Tags :