Skip to content

Allow type-level extraction of a class name as a string literal #43325

Closed
@poteat

Description

@poteat

Bug Report

Because class names cannot be modified and are known at compile time, they should be more narrowly typed.

🔎 Search Terms

  • class
  • name
  • constructor
  • string
  • literal
  • typeof
  • infer
  • narrow

🕗 Version & Regression Information

This behavior exists on Nightly (i.e. 4.3.0-dev.20210316) and the current version (4.2.3). It exists as far back as the compiler does - I was thereby not sure whether to classify this as a "bug" or a "feature request".

⏯ Playground Link

Playground link with relevant code

💻 Code

class Foobar {}

// @ts-ignore-error This emits an error as class names are readonly (as expected)
Foobar.name = "I can't name names"

// FooName is of type string rather than expected "Foobar"
type FooName = (typeof Foobar)["name"]

🙁 Actual behavior

FooName is of type string

🙂 Expected behavior

I would expect FooName to be inferred as type "Foobar", since the name cannot change (as per its readonly status).

A simple use-case would be a string-to-constructor record, but my use-case is actually generating sort of custom compiler error messages using string template literals. Right now I'm using the workaround of having a name attribute on each class, but it would be nice to not require that for my end-users.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions