gpt4 book ai didi

javascript - TypeScript 中的条件类型

转载 作者:行者123 更新时间:2023-12-02 13:46:14 25 4
gpt4 key购买 nike

我想知道 TypeScript 中是否可以有条件类型?

目前我有以下界面:

interface ValidationResult {
isValid: boolean;
errorText?: string;
}

但我想删除 errorText,并且仅当 isValidfalse 时将其作为必需属性.

我希望能够将其编写为以下接口(interface):

interface ValidationResult {
isValid: true;
}

interface ValidationResult {
isValid: false;
errorText: string;
}

但如您所知,这是不可能的。那么,您对这种情况有何看法?

最佳答案

对这种逻辑进行建模的一种方法是使用联合类型,如下所示

interface Valid {
isValid: true
}

interface Invalid {
isValid: false
errorText: string
}

type ValidationResult = Valid | Invalid

const validate = (n: number): ValidationResult => {
return n === 4 ? { isValid: true } : { isValid: false, errorText: "num is not 4" }
}

编译器然后能够根据 bool 标志缩小类型范围

const getErrorTextIfPresent = (r: ValidationResult): string | null => {
return r.isValid ? null : r.errorText
}

关于javascript - TypeScript 中的条件类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59172416/

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