I am faced with the challenge of dealing with field1 in my interface, which can have multiple data types: number, object, or boolean.
Currently, I have an if-condition to verify that the data type is a number before proceeding with data processing.
In cases 1 and 2, TypeScript correctly identifies field1 as a number type, but it fails to do so in case 3, which is the issue I am working on resolving in my project.
My goal is to make TypeScript recognize that in case 3, field1 is now a number type based on the result of isCorrectNumber. How can this be achieved?
I will need to utilize isCorrectNumber in various parts of the code.
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);
}