Skip to content

Apparent type of unknown when strictNullChecks=false causes odd errors on property access #47494

Open
@jakebailey

Description

@jakebailey

When strictNullChecks is disabled (as in JS code), destructuring a variable of type unknown produces the message:

Property 'foo' does not exist on type '{}'.(2339)

Whereas with it enabled, the error is:

Property 'foo' does not exist on type 'unknown'.(2339)

This behavior isn't actually tested anywhere, and was revealed in #47442.

When assigning unknown to a variable of some class type with properties, a similar error is produced:

Property 'prop' is missing in type '{}' but required in type 'A'.(2741)

Whereas strictNullChecks = true produces a more obvious error:

Type 'unknown' is not assignable to type 'A'.(2322)

This behavior (and other errors like it) is actually captured in a few tests.

This all seems to stem from the fact that getApparentType returns the empty object type as unknown's apparent type, which was added in #30637.

I would personally argue that the latter errors in the above examples make more sense than referring to {}, which doesn't actually appear in the code anywhere. Right now, this doesn't seem to be very visible (as people in JS are unlikely to see unknown), but with #47383 / #47442, this may become more visible.

const { foo } = {} as unknown;

function func({ foo }: unknown) {}

try {} catch ({ foo }) {}


class A {
    prop: number;
}

const a: A = {} as unknown;

Playground Link

Split off from #47442 (comment).

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions