Skip to content

Cannot use symbol as "index" for plain object property access #50319

Open
@mhofman

Description

@mhofman

Bug Report

{ [prop]() { } }[prop] fails with Type 'symbol' cannot be used as an index type. aka ts(2538) if prop: string | symbol. It works fine if prop is either string or symbol.

🔎 Search Terms

union type cannot be used as an index type

Found 2 somewhat relevant issues and a pull request, but they don't seem to directly apply. Please close if duplicate:

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about union and index types

⏯ Playground Link

Playground link with relevant code

💻 Code

declare function assert(condition: any, msg?: string): asserts condition;

function wrap(x: any) {
    return new Proxy(x, {
        get(_target, p, receiver) {
            return {
                [p](...args: any[]) {
                    assert(this === receiver);
                    return Reflect.apply(x[p], x, args);
                },
            }[p]
        },
        has() {
            return true;
        }
    });
}

declare const prop: string | symbol;

const shortHandFn = { [prop]() { } }[prop];

🙁 Actual behavior

Type 'symbol' cannot be used as an index type.

🙂 Expected behavior

No type error since both symbol and string are allowed index types.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions