gpt4 book ai didi

typescript - 是否可以有条件地要求 Typescript 接口(interface)中的属性

转载 作者:行者123 更新时间:2023-12-02 19:25:00 24 4
gpt4 key购买 nike

假设我有以下界面:

interface updateOptions {
updateAll: boolean;
fields: string[];
}

有没有办法在未提供 Fields 时要求 updateAll,反之亦然,或者这是否必须在实现中有条件地完成?

最佳答案

使用标记联合类型:

type UpdateOptions =
| {updateAll: true}
| {updateAll: false, fields: string[]}

这样你只能初始化{updateAll: true} 或者{updateAll: false, fields: ['someField',/*...*/]}

从技术上讲,联合不需要有标签( bool updateAll),但是你需要定义类型保护来测试在特定分支中使用的类型(我假设在你的代码中的某处你将执行 if (options.updateAll) {/* ... */}):

type UpdateAllOptions = {updateAll: true}
type UpdateSomeOptions = {fields: string[]}
type UpdateOptions = UpdateAllOptions | UpdateSomeOptions

// See https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
const isAllOptions = (options: UpdateOptions): options is UpdateAllOptions =>
(options as any).updateAll === true

关于typescript - 是否可以有条件地要求 Typescript 接口(interface)中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62502384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com