Skip to content

Non-null assertion operator and the typeof operator #17370

Closed
@bradzacher

Description

@bradzacher

TypeScript Version: 2.4.1

Code

// strictNullChecks: true

let x : string | undefined
let y = x!

type t1 = typeof x!
type t2 = typeof y

Expected behavior:
the t1 statement should create a type of type string.
the t2 statement should create a type of type string.

Actual behavior:
the t1 statement errors with ';' semicolon expected.
the t2 statement creates a type of type string.

There appears to be no way to achieve this without defining a separate variable, or by type guarding to remove the undefined / null.

With strict null checks on, this is especially troublesome in the case of generics with extends clauses, i.e.

class Foo {}
class Bar<T extends Foo> {}

const x : Foo | undefined

const y = new Bar<typeof x>() // throws an exception because typeof x === Foo | undefined != Foo

It would be great if the non-null assertion operator worked natively in typeof statements, or even if you could use brackets to resolve the assertion before the typeof.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions