如何使用打字稿使动态密钥可选

How to make a dynamic key optional with typescript

我想让动态密钥 item 可选。添加 ? 会产生错误。

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

您可以使用 type utilities PartialRecord 来创建您想要的类型:

TS Playground

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

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