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.
Thanks for you guys' help. Followed suggestions in comment area, so far my tsconfig.json is:
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"sourceMap": true,
"strictNullChecks": true,
"strict": true,
},
"exclude": [
"node_modules"
]
}
strictNullChecks option does work in TS playground, but it doesn't work in my local WebStorm either, also, I can compile my ts file via tsc demo.ts command. BTW this's my file constructor:
.
├── demo.js.map
├── index.html
├── demo.ts
├── demo.js
├── tsconfig.json