Dictionary or Map Type in TypeScript
![Dictionary or Map Type in TypeScript](/img/TypeScript/feature-image---dictionary-typescript.webp)
A dictionary or a map is used to quickly retrieve items from an object. TypeScript does not have any concept of map or dictionary.
Plain JavaScript has objects through which key-value pairs can be set and retrieved. TypeScript provides the Record
type, representing a dictionary or map through plain JavaScript objects.
The Record
type restricts the keys and values set in the plain JavaScript objects.
Use the Record
Type in TypeScript
The Record
type in TypeScript represents strict key-value pairs. More specifically, Record<K,V>
denotes that the object accepts only type K
and that the values corresponding to those keys should be type V
.
The key of Record<K,V>
would yield K
as the type, and Record<K,V>[K]
is equivalent to V
. The Record
type is an alias for index signatures like { [ key : K] : V }
.
The following code segment shows equivalent index signature type and Record
type structures used in TypeScript.
enum Level {
info = "info",
warning = "warning",
danger = "danger",
fatal = "fatal"
}
type LevelStrings = keyof typeof Level;
var bannerMessageInfo : Record<LevelStrings, string> = {
info : "[INFO]",
warning : "[WARNING]" ,
danger : "[DANGER]",
fatal : "[FATAL]"
};
function generateLogMessage(message : string , level : LevelStrings){
console.log(bannerMessageInfo[level] + " : " + message);
}
generateLogMessage("This is how Record Type can be used.", Level.info);
Output:
"[INFO] : This is how Record Type can be used."
The above Record
type can also be represented as an index signature.
type BannerTypeMap = {
[level in LevelStrings] : string;
}
var bannerMessageInfo : BannerTypeMap = {
info : "[INFO]",
warning : "[WARNING]" ,
danger : "[DANGER]",
fatal : "[FATAL]"
};
The BannerTypeMap
is a Mapped Type object in TypeScript, used here as an index signature and generated all the types of messages in bannerMessageInfo
.
In the above examples, all of the fields in the map are necessary, or else TypeScript may fail to compile. Partial types can be used with Record
types to create more robust ones.
Use Partial
With Record
Type in TypeScript
The Partial
keyword can override some initial default properties with some passed-on properties. The following code segment demonstrates this.
type PropStrings = 'height' | 'width' | 'shadow' ;
type Props = Record<PropStrings , number>
function CombineProps(props : Partial<Props> ){
var initProps : Props = {
height : 10,
width : 20,
shadow : 4
};
var finalProps = {...initProps , ...props};
console.log(finalProps);
}
CombineProps({width : 40});
Output:
{
"height": 10,
"width": 40,
"shadow": 4
}