How to Define a List of Optional Keys for Typescript Record ?
Last Updated :
08 Apr, 2024
In TypeScript, a Record is a utility type used to define objects with specific key-value pairs. In this article, we will explore two approaches to Define a list of optional keys for Typescript Record.
Using Partial<Type> for Optional Keys
We use TypeScript’s Partial<Type> to define optional keys in the obj type related to GeeksforGeeks, where opKeys specifies the specific optional keys like ‘title’, ‘author’, ‘likes’, ‘published’, and ‘category’, allowing them to have string, number, or boolean values.
Example: The below example uses Partial<Type> for Optional Keys to Define a list of optional keys for Typescript Record.
JavaScript
type opKeys = 'title' | 'author' | 'likes' | 'published' | 'category';
type obj = Partial<Record<opKeys, string | number | boolean>>;
const data: obj = {
title: 'GFG',
author: 'GeeksforGeeks',
likes: 100,
published: true,
category: 'Programming',
};
console.log(data);
Output:
{
"title": "GFG",
"author": "GeeksforGeeks",
"likes": 100,
"published": true,
"category": "Programming"
}
Using conditional types with keyof and Partial<Type>
We use conditional types in TypeScript, specifically Partial combined with Record<K, T[K]>, to define a list of optional keys (PartialKeys) for an object type (obj). This approach allows us to make only specified keys optional while retaining their original types.
Example: The below example uses conditional types with keyof and Partial<Type> to Define a list of optional keys for Typescript Record.
JavaScript
type obj = {
title: string;
author: string;
likes: number;
published: boolean;
category: string;
};
type PartialKeys<T, K extends keyof T> =
Partial<Record<K, T[K]>>;
type PartialObj = PartialKeys<obj, keyof obj>;
const data: PartialObj = {
title: 'GFG',
author: 'GeeksforGeeks',
likes: 100,
};
console.log(data);
Output:
{
"title": "GFG",
"author": "GeeksforGeeks",
"likes": 100
}
Share your thoughts in the comments
Please Login to comment...