Issue
I am new in Typescript. I am getting an error in which it is saying that the split does not exist on type number. Of course I have done the narrowing, by checking the type of value but it is of no use. Here is the code
file.ts
interface AIObject {
CLARITY_CODE?: string | {};
CARAT?: number | {};
SHAPE_CODE?: string | {};
}
const numericKeys = [
"CARAT",
];
const arrObj: AIObject[] = [
{
CLARITY_CODE: "DE",
CARAT: 5,
SHAPE_CODE: "SI",
},
];
arrObj.map((obj: AIObject) => {
let ov = Object.keys(obj);
ov.forEach((val) => {
if (typeof obj[val as keyof AIObject] === "string") {
const check = obj[val as keyof AIObject]?.split("-");
// console.log(check);
if (check.length === 2) {
if (numericKeys.includes(val)) {
obj[val as keyof AIObject] = { $gte: check[1], $lte: check[0] };
} else {
obj[val as keyof AIObject] = [...check];
}
}
}
});
});
Solution
Your issue is happening because your typeof
check on obj[val]
does not work as a type guard, like you are expecting. This is because there is no guarantee that obj[val] from the previous line will be the same when you use it later. Imagine an object with a custom getter for val
that returned an value of a random type: because it's being called twice, the compiler doesn't know that it will have the same type, because it's being told it could be a string, number, or object.
One solution is to create a variable with obj[val]
as its value, then your type guard will work as expected. Example
Another potential solution is to just cast the value to a string before you call .split()
. You know that it will be a string
, you just need the type system to accept it.
Answered By - smallpepperz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.