How to use a Function In Typescript
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: "w3wiki",
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: w3wiki
Description: A Computer Science Portal
Established Year: 2009
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.
Table of Content
- Using Dot Notation
- Using Bracket Notation
- Using a Function