Home > front end >  How to make a dynamic key optional with typescript
How to make a dynamic key optional with typescript

Time:02-10

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.
};

CodePudding user response:

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

  • Related