2023-02-11

Can a number type variable hold null value in Typescript without any potential problems?

I am new to Typescript. I came across a scenario where, my backend API may receive a null value in some cases. I intend to keep the variable type as "number" in the API code. Can this create any problem in hidden cases or it is good to go. If there is better way to deal with this, kindly let me know the snippet. Thank you in advance :)

const var1:number = null;    // here var1 can be number or a null

function test(param1:number){
  console.log(param1);
}

test(var1);

prints null but gives error as

Type 'null' is not assignable to type 'number' 


No comments:

Post a Comment