1

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).

0

2 Answers 2

2

What the TSConfig option strictNullChecks does is:

When strictNullChecks is false, null and undefined 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good thing to note that enabling strict is just a shortcut to enable all strictXXX checks
1

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'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.