Why do I get no error/warning when assigning an undefined
to a string
-typed constant in the following statement?
Why can I do
const s : string = undefined;
in non-strict mode, but can not do
const s: string = 5;
?
Is there a rule in Typescript specification that treats undefined
differently than number
when it comes to type checking?
(I understand I can turn the strict mode to enforce that, I'm curious about the mechanism that makes this possible in non-strict mode specifically).
CodePudding user response:
What the TSConfig option strictNullChecks
does is:
When
strictNullChecks
isfalse
,null
andundefined
are effectively ignored by the language. This can lead to unexpected errors at runtime.
So you're allowed to use undefined
where it wouldn't be permitted, but aren't allowed to use non-nullish, non-false values (like numbers or strings) where they wouldn't be permitted.
CodePudding user response:
When strictNullChecks is false, null and undefined are effectively ignored by the language. This can lead to unexpected errors at runtime.
When strictNullChecks is true, null and undefined have their own distinct types and you’ll get a type error if you try to use them where a concrete value is expected.
For example with this TypeScript code, users.find has no guarantee that it will actually find a user, but you can write code as though it will:
declare const loggedInUsername: string;
const users = [
{ name: "Oby", age: 12 },
{ name: "Heera", age: 32 },
];
const loggedInUser = users.find((u) => u.name === loggedInUsername);
console.log(loggedInUser.age);
Setting strictNullChecks to true will raise an error that you have not made a guarantee that the loggedInUser exists before trying to use it.
declare const loggedInUsername: string;
const users = [
{ name: "Oby", age: 12 },
{ name: "Heera", age: 32 },
];
const loggedInUser = users.find((u) => u.name === loggedInUsername);
console.log(loggedInUser.age);
// ~~~~~~~~~~~~ Object is possibly 'undefined'.