【发布时间】:2020-03-26 16:12:59
【问题描述】:
与类似问题的区别
在error TS2339: Property 'x' does not exist on type 'Y' 中,主题是indexable type。这不是,所以很可能需要其他解决方案。
问题
interface INumberPropertySpecification__CommonParameters {
readonly type: PROPERTIES_TYPES.NUMBER; // enum
readonly numberType: NUMBER_TYPES; // enum
}
export type NumberPropertySpecification =
INumberPropertySpecification__Required |
INumberPropertySpecification__HasDefault |
INumberPropertySpecification__Optional;
在上面的代码中,NumberPropertySpecification 是以下情况的并集:
- 该属性是必需的。在这种情况下,图书馆用户必须理解它,所以我让他明确指定
required: true
interface INumberPropertySpecification__Required extends INumberPropertySpecification__CommonParameters {
readonly required: true;
readonly invalidValueSubstitution?: number;
}
// Example:
const requiredNumberPropertySpecification: INumberPropertySpecification__Required = {
type: PROPERTIES_TYPES.NUMBER,
numberType: NUMBER_TYPES.ANY_REAL_NUMBER,
required: true // user MUST comprehend it, so I make him to explicitly specify it
}
- 该属性有默认值;这意味着它不是必需的。我不想让用户指定
required: false,因为这很明显。
interface INumberPropertySpecification__HasDefault extends INumberPropertySpecification__CommonParameters {
readonly defaultValue: number;
}
// Example
const requiredNumberPropertySpecification: INumberPropertySpecification__HasDefault = {
type: PROPERTIES_TYPES.NUMBER,
numberType: NUMBER_TYPES.ANY_REAL_NUMBER,
default: 1
}
- 该属性是可选的。在这种情况下,用户必须理解它,所以我让他明确指定
required: false:
interface INumberPropertySpecification__Optional extends INumberPropertySpecification__CommonParameters {
readonly required: false;
}
// Example:
const requiredNumberPropertySpecification: INumberPropertySpecification__Optional = {
type: PROPERTIES_TYPES.NUMBER,
numberType: NUMBER_TYPES.ANY_REAL_NUMBER,
required: false // user MUST comprehend it, so I make him to explicitly specify it
}
错误
我们无法检查targetPropertySpecification.required === true。在这种情况下,TypeScript 类型检查算法就大材小用了,因为当 targetPropertySpecification.required 未定义时,不会发生 JavaScript 错误(即使只是 if(targetPropertySpecification.required),但使用 "@typescript-eslint/strict-boolean-expressions": 的人不能写这样的)。
与defaultValue(isUndefined)相同的歌曲:
【问题讨论】:
标签: typescript typescript-typings