如何使用打字稿使动态密钥可选
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 Partial
和 Record
来创建您想要的类型:
type Example = Partial<Record<string, unknown>> & { name?: string };
declare const example: Example;
example.name; // string | undefined
example.anyOtherProperty; // unknown
我想让动态密钥 item
可选。添加 ?
会产生错误。
type Example = {
name?: string;
[item: string]?: unknown; // error: TS1131: Property or signature expected.
};
您可以使用 type utilities Partial
和 Record
来创建您想要的类型:
type Example = Partial<Record<string, unknown>> & { name?: string };
declare const example: Example;
example.name; // string | undefined
example.anyOtherProperty; // unknown