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

Support type inference for Symbol keys on function #61214

Open
6 tasks done
Bernhard-Kodio opened this issue Feb 18, 2025 · 0 comments Β· May be fixed by #61232
Open
6 tasks done

Support type inference for Symbol keys on function #61214

Bernhard-Kodio opened this issue Feb 18, 2025 · 0 comments Β· May be fixed by #61232

Comments

@Bernhard-Kodio
Copy link

πŸ” Search Terms

symbol index closure function ts7022

βœ… Viability Checklist

⭐ Suggestion

Typescript doesn't correctly infer the type when using a symbol as the key when adding a property to a function type.

Here is an example:

const TestSymbol: unique symbol = Symbol();

const c = () => {
  return 'Hello, world!';
};
c['testProp'] = ['Hello']; // String property is correctly inferred to be of the type string[]
c[TestSymbol] = ['Hello']; // Typescript complains about the type being implicitly any.

c[TestSymbol] = ['Hello'] as string[] // This works as a workaround for this limitation in typescript.

The full error from the language server:

c[TestSymbol] implicitly has type 'any' because it does not have a type annotation
and is referenced directly or indirectly in its own initializer. (tsserver 7022)

Using a symbol this way works without any issues in plain javascript. I've tested Firefox, Chromium, Node and Bun and all these runtimes handle using symbols as property keys on a function without any issue.

It is very limiting not being able to use symbols naturally in typescript the same way they work in javascript. It would be great if typescript could infer the type of the property when using a symbol as the key the same way it does when using a string for the key.

πŸ“ƒ Motivating Example

I've not written any blog posts about this.

πŸ’» Use Cases

  1. What do you want to use this for? I'm building some infrastructure code where I want to append some information to various objects. Using symbols removes the risk of key collisions that can occur when using strings.
  2. What shortcomings exist with current approaches? Using strings instead of symbols or manually casting to the expected type can lead to unexpected collisions and type errors.
  3. What workarounds are you using in the meantime? Strings and manually casting to the expected type.
@Bernhard-Kodio Bernhard-Kodio changed the title Support type inference for Symbol keys on closure Support type inference for Symbol keys on function Feb 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant