我的 TypeScript 项目中有一个类型
export type Types = "APPLE" | "MANGO" | "BANANA";
这里我希望 BANANA 是可选的,即
例如,如果我使用类型中的键创建了映射
const MAPPING: { [key in Types]: string } = {
APPLE: "Here is Apple",
MANGO: "Here is Mango",
};
此代码给出错误,它要求为每个键定义映射,如果我不这样做,则会给出错误:
Property 'BANANA' is missing in type '{ APPLE: string; MANGO: string; }' but required in type '{ APPLE: string; MANGO: string;
BANANA: string; }'
为了避免这些类型的错误,我想让 BANANA 成为可选的,而且我不想更改 MAPPING 本身,它应该保留为 [key in Types]。我明白是使用
Exclude
还是 Types
?可以,但这需要更改很多文件。
还有其他方法可以达到这个目的吗?
您可以使用交叉路口:
export type Types = "APPLE" | "MANGO" | "BANANA";
type MakeOptional<T extends string, E extends string, V = any> = {
[K in Exclude<T, E>]: V
} & {
[K in E]: V
};
type Mapped = MakeOptional<Types, 'BANANA'>
const MAPPING: { [key in Types]?: number } = { APPLE: 1 };