When I use a separate function like isNum, TypeScript throws wrong red highlights in vscode. (compiler error)
for instance,
// in some file
const print = (param: number) => {
console.log(param);
};
const isNum = (num: unknown): boolean => {
return typeof num === 'number';
};
if (isNum(a)) print(a);
// in some other file
export const a: number | null = 1;
a
in print(a)
is red highlighted and it says “Argument of type ‘number | null’ is not assignable to parameter of type ‘number’.”
I believe it shouldn’t happen because isNum function ensures it returns true when the given value is number.
The weird thing is when it’s inline, it works
const print = (param: number) => {
console.log(param);
};
if (typeof a === 'number') print(a);
could you tell me why it is? am i missing something?
and could you recommend good way to resolve this?
fyi, I don’t want to use type assertion. because I think it harms readability.
I don’t want to do inline checking neither.
my tsconfig file
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": false,
"strictBindCallApply": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": false,
"esModuleInterop": true,
"noEmitOnError": true
},
}
Thank you!