How to Extend the Possible Types of Values of Dictionary in TypeScript ?
Last Updated :
31 Jul, 2024
A dictionary in TypeScript is a data type that can store the data in the form of key-value pairs. The dictionaries in TypeScript can be created using the type keyword, Interfaces, or simple objects. The type of the values in a dictionary can be predefined in TypeScript which can be extended to store values of different kinds. Let us discuss different ways to extend possible types of values of the dictionary.
By using Generics
The generic type can be used directly to declare a dictionary with extended value type by specifying them at the time of creating instances of that dictionary.
Syntax:
type dictionaryName<T> = {
key: T;
};
Example: The below code example creates a dictionary with extended types of values using generic type.
JavaScript
type myDictionary<T> = {
[key: string]: T;
}
const dictionaryObj1: myDictionary<string> = {
name: "GeeksforGeeks",
desc: "A Computer Science Portal"
}
const dictionaryObj2: myDictionary<boolean> = {
isGeeksforGeeks: true,
}
if (dictionaryObj2.isGeeksforGeeks) {
console.log(dictionaryObj1);
}
Output:
name: "GeeksforGeeks",
desc: "A Computer Science Portal"
Using Union types
The union type can be used to specify the multiple types for the values of a key in TypeScript dictionary. Different types will be seprated using the straight line (|).
Syntax:
type dictionaryName = {
key: typesSeparatedUsingStraightLine;
}
Example: The below code will explain the way of defining the dictionaries with multiple type values.
JavaScript
type myDictionary = {
[key: string]: number | string | boolean;
}
const dictionaryObj1: myDictionary = {
name: "GeeksforGeeks",
desc: "A Computer Science Portal",
workForce: 200
}
const dictionaryObj2: myDictionary = {
isGeeksforGeeks: true,
}
if (dictionaryObj2.isGeeksforGeeks) {
console.log(
`Company Name: ${dictionaryObj1.name}
Description: ${dictionaryObj1.desc}
Workforce: ${dictionaryObj1.workForce}+`);
}
Output:
Company Name: GeeksforGeeks
Description: A Computer Science Portal
Workforce: 200+
By mapping types
We can specify the different types for the values inside the object passed as generic type to the dictionary which can mapped or iterated to set types of the values.
Syntax:
type dictionaryName<T> = {
[keyType in keyof T]: any;
}
Example: The below code maps the types of the values for each key in TypeScript dictionary.
JavaScript
type myDictionary<T> = {
[keyType in keyof T]: any;
}
const dictionaryObj1: myDictionary<{
name: string;
desc: string;
workForce: number;
isGeeksforGeeks: boolean;
}> = {
name: "GeeksforGeeks",
desc: "A Computer Science Portal",
workForce: 200,
isGeeksforGeeks: true
}
if (dictionaryObj1.isGeeksforGeeks) {
console.log(
`Company Name: ${dictionaryObj1.name}
Description: ${dictionaryObj1.desc}
Workforce: ${dictionaryObj1.workForce}+.`);
}
Output:
Company Name: GeeksforGeeks
Description: A Computer Science Portal
Workforce: 200+
Using Intersection Types
Intersection types in TypeScript allow you to combine multiple types into one, ensuring that a dictionary can accept values of any type that is an intersection of the specified types. This method is useful for extending the possible types of values in a dictionary while maintaining type safety.
Syntax:
type Dictionary<T, U> = {
[key: string]: T & U;
};
Example: The following example demonstrates how to use intersection types to extend the possible types of values in a dictionary. By intersecting two types, Person and Contact, the dictionary can store values that conform to both types.
JavaScript
type Person = {
name: string;
age: number;
};
type Contact = {
phone: string;
email: string;
};
type Dictionary<T, U> = {
[key: string]: T & U;
};
const dictionaryObj: Dictionary<Person, Contact> = {
entry1: {
name: "Nikunj Sonigara",
age: 22,
phone: "123-456-7890",
email: "[email protected]"
},
entry2: {
name: "Dhruv Sonigara",
age: 17,
phone: "098-765-4321",
email: "[email protected]"
}
};
console.log(dictionaryObj.entry1.name); // Output: Nikunj Sonigara
console.log(dictionaryObj.entry2.phone); // Output: 098-765-4321
console.log(dictionaryObj.entry1.email); // Output: [email protected]
Similar Reads
How to Strongly Type the Return Value of any Function in TypeScript ?
Specifying the return type after a function's parameters with a colon ensures a consistent return value type. This enhances code reliability by enforcing expected return types. It is a fundamental feature of TypeScript that ensures functions consistently produce values of the specified type. The bel
2 min read
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 NotationUsing Bracket NotationUsing a Funct
2 min read
How to Sort a Dictionary by Value in TypeScript ?
In TypeScript, dictionaries are objects that store key-value pairs. Sorting a dictionary by value involves arranging the key-value pairs based on the values in ascending or descending order. The below approaches can be used to accomplish this task: Table of Content Using Object.entries() and Array.s
2 min read
How to Create Union of Generic Types that Extend String in TypeScript ?
Creating a union of generic types that extend string in TypeScript involves defining a type that accepts only string literals. This allows for the creation of a type that represents a specific set of strings, providing type safety and flexibility in code. These are the following ways to do that: Tab
5 min read
How to create conditional types in TypeScript ?
Conditional types in TypeScript enable defining types based on conditions, similar to conditional statements in code. They determine different types of values, making functions adaptable to various input types, and enhancing code flexibility and maintainability. Syntax: We can create conditional typ
3 min read
How to Get an Object Value By Key in TypeScript
In TypeScript, we can get an object value by key by accessing the specific properties within the objects of the dynamic type. This can be done using Dot Notation, Bracket Notation, and Optional Chaining. In this article, we will explore all these approaches along with their implementation in terms o
5 min read
How to Access Dictionary Value by Key in TypeScript ?
Dictionaries are often represented as the objects where keys are associated with the specific values. These TypeScript dictionaries are very similar to JavaScript objects and are used wherever data needs to be stored in key and value form. You can use the below method to access the dictionary values
2 min read
How to Derive Union Type From Tuple/Array Values in TypeScript ?
This article will show how to derive union type from tuple/array values in TypeScript language. The union type in TypeScript is mainly formed by combining multiple types. We will see various approaches through which we can derive union type. Below are the possible approaches: Table of Content Using
2 min read
Find the Length of a Dictionary in TypeScript
In TypeScript, to find the length of a dictionary, there is no built-in property for objects that determines the length of the dictionary. The length of the input dictionary can be retrieved by counting the pairs of key values in it. There are several approaches available in TypeScript for finding t
4 min read
How to Test if Two Types are Exactly the Same in TypeScript ?
This article will show how we can test if the two types are the same in TypeScript. Types in Typescript are used to define and describe the data in our code. Some of the types are number, string, boolean, etc. Below are the possible approaches: Table of Content Using extends and keyofUsing Extract a
3 min read