Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial keys of union type as key of an object in typescript

I want to use the keys of the union type as key of the object in typescript.

type EnumType = 'a1' | 'a2'

const object:{[key in EnumType]: string}= {
 a1: 'test'
}

In this case I have to add even a2 as a key in the object. Is there a way to make this optional?

Playground

like image 869
Jibin Thomas Avatar asked Jan 25 '23 16:01

Jibin Thomas


2 Answers

Just add a question mark like this:

type EnumType = 'a1' | 'a2'

const object:{[key in EnumType]?: string}= {
 a1: 'test'
}

The object definition with your current code:

const object: {
    a1: string;
    a2: string;
}

Becomes:

const object: {
    a1?: string | undefined;
    a2?: string | undefined;
}

Allowing every key to be optional.

like image 99
Guerric P Avatar answered Jan 27 '23 06:01

Guerric P


please use Utility Types

type EnumType = "a1" | "a2";

const object: Partial<Record<EnumType, string>> = {
  a1: "test",
};

like image 41
ZOFFY Avatar answered Jan 27 '23 04:01

ZOFFY