I'm a new comer in typescript, and I learnt that we can not assign Type 'string | undefined' to Type 'string' from internet tutorials like https://linguinecode.com/post/how-to-solve-typescript-possibly-undefined-value. But when I write a demo on WebStorm, I found it can be compiled, without any errors, and also can run. This totally confused me.
Here is my TS code:
function validateToken(token: string) {
return token;
}
function run() {
const token = 'kjadj' as string | undefined;
let a = validateToken(token);
console.log(a)
}
after compile , it became below JS code:
function validateToken(token) {
return token;
}
function run() {
var token = 'kjadj';
var a = validateToken(token);
console.log(a);
}
My typescript version is 4.7.4, WebStorm version is Build #WS-221.5921.27, built on June 22, 2022.
CodePudding user response:
Inside the compiler options you should set "strict": true. You can check the docs here.
CodePudding user response:
You need to activate strictNullChecks
To test out how differnt typescript configs behave you can use your sample in typescriptPlayground. Under the "TS Config" dropdown you can easily swap settings ;)