Reputation: 123560
I am specifying types on a function. TypeScript types are (as of current TypeScript versions) non-nullable by default. However I don't get any errors when I run a function with null
or undefined
.
function sayHello(name: string){
console.log(`Hello ${name}`)
}
In the code above sayHello(undefined)
and sayHello(null)
should both fail.
What they currently do in TypeScript 3.8.3:
Hello null
Hello undefined
vsCode gives no warnings:
Why is TypeScript not warning when setting a non-nullable value as null?
Upvotes: 7
Views: 2599
Reputation: 44417
Not nullable is now the default in TypeScript. You should get the typescript compilation error:
Argument of type 'null' is not assignable to parameter of type 'string'. ts(2345)
If you don't get that, you may want to take a look at your compiler options. I would recommend the strict
option.
You can set that up with a tsconfig.json
file containing something like this:
{
"compilerOptions": {
"strict": true,
},
}
Upvotes: 3
Reputation: 2013
Do you have a tsconfig.json
file? If so, how does it look like?
Make sure, you have following entries in your tsconfig.json
(shortened for the sake of brevity):
{
"compilerOptions": {
"strictNullChecks": true
}
}
From the TypeScript doc:
strictNullChecks
: switches to a new strict null checking mode.
Upvotes: 8