Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mhofman opened this issue Aug 16, 2022 · 1 comment
Open

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

mhofman opened this issue Aug 16, 2022 · 1 comment
Labels
Bug A bug in TypeScript
Milestone

Comments

@mhofman
Copy link

mhofman commented Aug 16, 2022

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.

@RyanCavanaugh RyanCavanaugh added the Bug A bug in TypeScript label Aug 17, 2022
@RyanCavanaugh RyanCavanaugh added this to the Backlog milestone Aug 17, 2022
@icecream17
Copy link

icecream17 commented Oct 22, 2022

ts(2538) ts2538
Also ran into this

https://www.typescriptlang.org/play?target=99#code/GYVwdgxgLglg9mABAWwIYGsCmAxc15gDqMUAFgHKrKaIAUYVmAXIgAoBOcADpu1AJ4BpTPwCUiAN4AoRLMTtMUEOyTS56xAG0G1ALota4gLwA+ROAAmmYDDCYLMuQF9tjXVKdSgA

function makeFunctionWithName (name: PropertyKey) {
    return {
        [name]: () => undefined
    }[name]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants