I have 2 variables a & b;
const a:string | undefined = undefined;
const b:string | undefined = undefined;
Those variables get passed as arguments to 2 different functions. Function 1 checks to see if a & b are undefined and returns false if they are, if not it returns true.
const checkIfUndefined = (a:undefined | boolean,b:undefined | boolean):boolean =>{
if((a && b) === undefined){
return false;
}
return true
}
I am using both of the functions with a turnery operator like this:
checkIfFalse(a,b) ? log(a,b) : null;
the second function (log) still throws an error because it still thinks a & b are undefined even though second function will only get run if checkIfFalse function will return true.
Is there a way to work around this in typescript?
This is the error im getting:
Argument of type 'undefined' is not assignable to parameter of type 'boolean'.(2345)
CodePudding user response:
The problem is that checkIfFalse(a,b)
does not assert that a
and b
are indeed not undefined
.
You can use a custom type guard to adjust your checkIfUndefined
method:
const checkIfUndefined = (a_value: string | undefined): a_value is string => {
return a_value !== undefined;
}
This function asserts that a_value
is a string
, so you'd be able to do this:
const log = (a:string) => {
console.log(a);
}
checkIfUndefined(a) ? log(a) : null;
And combined:
const a:string | undefined = undefined;
const b:string | undefined = undefined;
const checkIfUndefined = (a_value: string | undefined): a_value is string =>{
return a_value !== undefined;
}
const log = (a:string,b:string) =>{
console.log(a,b);
}
checkIfUndefined(a) && checkIfUndefined(b) ? log(a, b) : null;
CodePudding user response:
Variables a and b are of type string or undefined, in methods you are accepting values of a and b as boolean | undefined