如何使用打字稿使动态键可选

eto*_*xin 0 typescript typescript-typings

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

type Example = {
  name?: string;
  [item: string]?: unknown; // error: TS1131: Property or signature expected.
};
Run Code Online (Sandbox Code Playgroud)

jse*_*ksn 5

您可以使用类型实用程序 PartialRecord创建所需的类型:

TS游乐场

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

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

Run Code Online (Sandbox Code Playgroud)