etoxin
etoxin

Reputation: 5294

How to make a dynamic key optional with typescript

I would like to make the dynamic key item optional. Adding ? creates an error.

type Example = {
  name?: string;
  [item: string]?: unknown; // error: TS1131: Property or signature expected.
};

Upvotes: 2

Views: 2423

Answers (2)

muwonge nicholus
muwonge nicholus

Reputation: 144

You could create a type for the dynamic item and make it optional using Partial like below.

type DynamicItemtype = { 
  [item: string]: unknown;
}

Then add both types into another type as an intersection type like

type Example = {
  name?: string
}

type CombinedTypes = Example & Partial<DynamicItemtype>

Upvotes: -1

jsejcksn
jsejcksn

Reputation: 33921

You can use the type utilities Partial and Record to create the type you want:

TS Playground

type Example = Partial<Record<string, unknown>> & { name?: string };

declare const example: Example;
example.name; // string | undefined
example.anyOtherProperty; // unknown

Upvotes: 5

Related Questions