Search code examples
typescripttypes

Why is the type {} inferred instead of unknown when strictNullChecks is disabled?


Consider the following code:

const { name } = "something" as unknown;

When I enable Typescript's strictNullChecks, I get the following error message:

Error: Property `name` does not exist on type `unknown`

Which sounds about right.

But when I disable strictNullChecks, I get the following error message:

Error: Property `name` does not exist on type `{}`

What does {} mean here?

I only know {} as non-nullish value. But why is it inferred here instead of unknown?


Solution

  • What does {} mean here? I only know {} as non-nullish value. But why is it inferred here instead of unknown?

    When strictNullChecks is false, null and undefined might as well not exist; they're ignored by the language. As you said {} means a non-nullish value, and if null and undefined don't exist, that's everything. So when strictNullChecks are turned off, {} and unknown are equivalent.