我想知道我是否可以在TypeScript中使用条件类型?
目前,我有以下界面:
interface ValidationResult {
isValid: boolean;
errorText?: string;
}
但是我想删除errorText
,并且仅在isValid
is false
作为必需属性时使用它。
我希望能够将其编写为以下界面:
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" }
}
然后,编译器能够根据布尔标志缩小类型
const getErrorTextIfPresent = (r: ValidationResult): string | null => {
return r.isValid ? null : r.errorText
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句