Skip to content

Computed key in get, set declarations incorrectly reported as non-key type #51890

Closed
@cefn

Description

@cefn

Bug Report

Use of a computed property name in a getter or setter leads to unexpected error A computed property name must be of type 'string', 'number', 'symbol', or 'any' even when the computed type does satisfy these types.

If this should be considered a feature report, (e.g. this is a known gap in the language, but just a misleading error) one motivating use case for improving the support of get and set could be achieving future strictness preventing readonly assigned to mutable.

In the short term (before readonly strictness), being able to use get with mapped types and computed property names and value types would mean that there are workarounds for cases when you want to PREVENT the passing of writeable objects and maybe warn that the object should have been readonly, as demonstrated in the imaginary Frozen<T> implementation in the code sample.

🔎 Search Terms

getter setter "computed property name"

🕗 Version & Regression Information

I don't know of a version this works with. Everything up to the Nightly at the time of writing experiences this bug.

⏯ Playground Link

Playground demonstrating error

💻 Code

// FIXED FIELDS - COMPILES

type HasFixedField = {
  propName:boolean
}

type HasFixedGetter = {
  get propName():boolean
}

type HasFixedSetter = {
  set propName(value:boolean)
}

// COMPUTED FIELDS - COMPILE ERROR

type HasGenericField<K extends string, V> = {
  [k in K]: V;
}

type HasGenericGetter<K extends string, V> = {
  get [k in K]() : V;
}

interface HasGenericSetter<K extends string, V> {
  set [k in K](value:V)
}

interface HasNoGenericSetter<K extends string>{
  set [k in K]:never
}

type Frozen<T> = keyof T extends string ? HasGenericGetter<keyof T, T[keyof T]> & HasNoGenericSetter<keyof T> : never

🙁 Actual behavior

Hovering over the error in the get or set definitions (which are identical to the working property definition above) leads to these errors...

A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
Cannot find name 'k'
'K' only refers to a type, but is being used as a value here.

🙂 Expected behavior

I would expect it to be possible to define the presence and absence of getters and setters using computed property names.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions