Ad

How To Make A Dynamic Key Optional With Typescript

- 1 answer

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

Answer

You can use the type utilitiesPartial 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

Ad
source: stackoverflow.com
Ad