我有一个与field1的接口,该接口具有多种可能的数据类型:数字、对象或布尔型.
在处理数据之前,我有If-Condition来判断数据类型是否为Numbers.
对于Case1和Case2,类型脚本正确识别字段1现在是一个数字类型,但不是在Case3上,这是我试图在我的项目中解决的问题.
How to Get TypeScrip知道,在 case 3中,field1现在是基于isGentNumber结果的数字类型?
我需要在不同的地方使用isGentNumber
interface Module1 {
field1: number | {key: string; value: string}[] | boolean;
}
const value: Module1 = {
field1: [{key: 'key', value: 'value'}]
};
if (typeof value.field1 === 'number' && value.field1 % 2 === 0 && (value.field1 > 0 || value.field1 < 100)) {
const myString: number = value.field1; // Case1: WORKS
console.log(myString);
}
const isCorrectNumberFn = (value: Module1): value is {field1: number} => (typeof value.field1 === 'number' && value.field1 % 2 === 0&& (value.field1 > 0 || value.field1 < 100));
if (isCorrectNumberFn(value)) {
const myString: number = value.field1; // Case2: WORKS
console.log(myString);
}
const isCorrectNumber = typeof value.field1 === 'number' && value.field1 % 2 === 0&& (value.field1 > 0 || value.field1 < 100);
if (isCorrectNumber) {
const myString: number = value.field1; // Case3: ERROR: Type 'number | boolean | { key: string; value: string; }[]' is not assignable to type 'number'. Type 'boolean' is not assignable to type 'number'
console.log(myString);
}