如何在 Union Type 中将 key 设置为可选

问题描述 投票:0回答:2

我的 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
?可以,但这需要更改很多文件。

还有其他方法可以达到这个目的吗?

javascript typescript
2个回答
0
投票

您可以使用交叉路口:

游乐场

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'>

0
投票
const MAPPING: { [key in Types]?: number } = { APPLE: 1 };
© www.soinside.com 2019 - 2024. All rights reserved.