You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Type 'symbol' cannot be used as an index type. #24587
Expected behavior:
No errors. tsc --target es6 symbol-index.ts works with 2.8.4.
Actual behavior: symbol-index.ts(4,3): error TS2538: Type 'symbol' cannot be used as an index type.
when running tsc --pretty false --target es6 symbol-index.ts with 2.9.1 or next.
Reacted by Ruben Anders, Sergey M., Eugene, Telokis, Anton Savchenko, Lukas Eibensteiner, Roger Padilla, 守卫, Mingwei Samuel, Danylo Bilokha and 16 more
we forbid symbols as indexers because we have no symbol index signatures (this was a hole we patched in 2.9 - previously it would assume the string indexer type, which was very incorrect), however unique symbols - a type associated with exactly one symbol are fine, since they refer to exactly one property.
Reacted by wpq0dev, dhomochevsky and saifuddin
Reacted by Eugene, Dave Campion, MYTAC, Jerry.Z, H2rmone, Mingwei Samuel, Heartlander, Chris Kinzel, zsqsmart, Robert Monfera and 30 more
Yeah.... We don't have symbol index signatures, and a Record<whatever, string> isn't going to have any specific symbol named properties. Suffice to say, right now there's no way in the typesystem to make a type which can have arbitrary symbol keys. There's an issue for it open... #1863 I think.
Shouldn't you always be able to index a property by PropertyKey (by definition)? Given that PropertyKey is string | number | symbol, I think it should follow that indexing by a symbol should always be possible.
Oddly enough, the following works:
letx: {[keyinsymbol]: string};// typeof x is {}x[Symbol()]=newDate();x['hello']='world';
But this doesn't:
letx: {[keyinsymbol|string]: string};// typeof x is { [key: string]: string } x[Symbol()]='value';x['hello']='world';
Reacted by Sergey M., Karel Hrkal, WorldSEnder and dominictobias
I don't know how to feel about it, personally, but it's been "a way out" of the type checker for awhile. Usages are an error under noImplicitAny, so it doesn't come up too often.
But this doesn't
Yeah, since the mapped type maps over string, it manufactures a string index signature in the resulting type. Since symbols can't have index signatures, it quietly drops them (for now, at least).
Reacted by Juan Picado, Dennis Brown, Patrick Roberts and Azamat G
I have a question which is similar to this issue, I believe.
I author a library containig a similar class like MyObject you will find below. One main feature is that the content of MyObject can be different depending on the content. To enable users to write something like myObject.test I added the property [key: string]: any; to the interface.
With typescript 2.9.x this will result in Type 'unique symbol' cannot be used as an index type. error, but wenn I remove this line users will get Property 'test' does not exist on type 'MyObject'. when trying to access anything "dynamically added".
Is there any way of doing this properly?
edit:
It seems I found a workaround. If i declare the symbol const sbl: any = Symbol.for('content') typescript will accept it.
constsbl: any=Symbol.for('content');// With `any` it will workinterfaceMyObject{someProperty: string;another: number;[key: string]: any;}classMyObject{constructor(content: any){this[sbl]=content;// Type 'unique symbol' cannot be used as an index type.Object.keys(content).forEach((key)=>{// This is in fact more complex ;-)Object.defineProperty(this,key,{get: ()=>this[sbl][key],set: (val: any)=>this[sbl][key]=val,});});}}exportdefaultMyObject;constobj=newMyObject({test: 'content'});console.log(obj.test);// Property 'test' does not exist on type 'MyObject'.
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
Reacted by Ruben Anders, Nic Barker, Sergey M., Reinis Ivanovs, Kael, Telokis, Acid Chicken, Dave Campion, Thonio, Erik and 52 more
constsbl=Symbol('content');interfaceMyObject<T>{someProperty: string;another: number;[sbl]: T;[key: string]: any;}classMyObject<T>{constructor(content: T){this[sbl]=content;Object.keys(content).forEach((key)=>{// This is in fact more complex ;-)Object.defineProperty(this,key,{get: ()=>this[sbl][key],set: (val: any)=>this[sbl][key]=val,});});}}exportdefaultMyObject;constobj=newMyObject({test: 'content'});console.log(obj.test);// `any`
Wesley Wigham (@weswigham)Mohamed Hegazy (@mhegazy) Do we have any spec that describes that this behavior is intended?
For now, the main point that I get from #24587 (comment) is that we forbid symbols as indexers because we have no symbol index signatures and for me it's sounds like bug in compiler because:
According to refs above consider following use case. I am implementing DI container where i would like to provide library users ability to use Symbols as keys(to avoid components collision) for their components. In my code I have something like: interface ComponentsContainer { [key: PropertyKey]: Component; }
Could someone provide strong argumentation why it's not a bug in compiler and this code shouldn't work?
Reacted by Denys Lapin, Andrii Tiertyshnyi, Vitalii Homonov, arturohernandez10, Oleksii Gontar, frontend_vladyslav, Dmitry Melnik, Matt Forster, Fenying, Joshua and 74 more
Reacted by Emmanuel Leitão Daher, Reinis Ivanovs, Anton Gorbikov, NN, Doniyor Aliyev, Telokis, Robert Collins, John Leidegren, Eugene, Jason Athanasoglou and 21 more
Reacted by Frédéric Bonnet, Jason Athanasoglou, George Yong, Mayo Tobita, Adrian Miranda, Iván Arcuschin, Tyler Haigh, GlyphCat, blt-r, Michał Wadas and 4 more
Reacted by Arslan Charyyev, Michal Filip, Jason Athanasoglou, Erik, Bernát Gyovai, George Yong, dominictobias, Simon Guo and Mohammad Mojtaba Roshani - mmRoshani (TOMaaR)
Reacted by Igor, Ali Mihandoost (علی میهندوست), Mayo Tobita, Maxie and Thor-Björn Andersson
Can't imagine how it could be marked as "work as intended", since we have this "TypeScript is a typed superset of JavaScript" on main page. This is definitely a bug in a type system and should be fixed somehow.
Reacted by Sven Mol, Arutyunyan Artyom, Reinis Ivanovs, Jason Athanasoglou, Mohammad Fakhreddin, Janealter, Aleksey Levenstein, Chayim Refael Friedman, Ariel Shaqed (Scolnicov), Martin Cissel and 72 more
Reacted by Erik, Jason Leo, Sʜɪᴍᴜʀᴀ Yū, dominictobias and Leonardo Raele
Reacted by Jason Athanasoglou, Mohammad Fakhreddin, Erik, Aleksey Levenstein, Martin Cissel, rosinfo.tech, Chris Kinzel, Jason Leo, Caelan Stewart, Lays Dragon and 3 more
Activity
weswigham commentedon Jun 1, 2018
@prshreshtha just write
or if you must type annotate, write
we forbid symbols as indexers because we have no symbol index signatures (this was a hole we patched in 2.9 - previously it would assume the string indexer type, which was very incorrect), however unique symbols - a type associated with exactly one symbol are fine, since they refer to exactly one property.
praihan commentedon Jun 1, 2018
Wesley Wigham (@weswigham) both of your suggestions produce
symbol-index.ts(4,3): error TS2538: Type 'unique symbol' cannot be used as an index type.Playground Link: http://www.typescriptlang.org/play/#src=const%20x%3A%20Record%3Ckeyof%20any%2C%20string%3E%20%3D%20%7B%7D%3B%0D%0Ax%5B'hello'%5D%20%3D%20'world'%3B%0D%0Aconst%20sym%20%3D%20Symbol('sym')%3B%0D%0Ax%5Bsym%5D%20%3D%20'symbol%20string'%3B%0D%0A%0D%0Aconst%20sym2%3A%20unique%20symbol%20%3D%20Symbol('sym')%3B%0D%0Ax%5Bsym2%5D%20%3D%20'symbol%20string'%3B
weswigham commentedon Jun 1, 2018
Yeah.... We don't have symbol index signatures, and a
Record<whatever, string>isn't going to have any specific symbol named properties. Suffice to say, right now there's no way in the typesystem to make a type which can have arbitrary symbol keys. There's an issue for it open... #1863 I think.praihan commentedon Jun 1, 2018
Hmm. So this code working pre
2.9is a bug?Shouldn't you always be able to index a property by
PropertyKey(by definition)? Given thatPropertyKeyisstring | number | symbol, I think it should follow that indexing by asymbolshould always be possible.Oddly enough, the following works:
But this doesn't:
weswigham commentedon Jun 1, 2018
Conceptually yes - the actual machinery to make it work was never in place - the symbols were just being mistaken for strings.
Yeah, that's because square bracket accesses to
{}are unchecked:I don't know how to feel about it, personally, but it's been "a way out" of the type checker for awhile. Usages are an error under
noImplicitAny, so it doesn't come up too often.Yeah, since the mapped type maps over
string, it manufactures astringindex signature in the resulting type. Sincesymbols can't have index signatures, it quietly drops them (for now, at least).praihan commentedon Jun 1, 2018
Got it. Thanks for the detailed explanation.
simon-scherzinger commentedon Jun 6, 2018
Wesley Wigham (@weswigham)
I have a question which is similar to this issue, I believe.
I author a library containig a similar class like
MyObjectyou will find below. One main feature is that the content ofMyObjectcan be different depending on thecontent. To enable users to write something likemyObject.testI added the property[key: string]: any;to the interface.With typescript 2.9.x this will result in
Type 'unique symbol' cannot be used as an index type.error, but wenn I remove this line users will getProperty 'test' does not exist on type 'MyObject'.when trying to access anything "dynamically added".Is there any way of doing this properly?
edit:
It seems I found a workaround. If i declare the symbol
const sbl: any = Symbol.for('content')typescript will accept it.typescript-bot commentedon Jun 25, 2018
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
weswigham commentedon Jun 25, 2018
Simon Scherzinger (@simon-scherzinger) You probably want something more along the lines of
Fall back to TypeScript 2.8, as 2.9 currently generates a raft of spu…
AlexeiGontarCyber commentedon Aug 8, 2018
Wesley Wigham (@weswigham) Mohamed Hegazy (@mhegazy) Do we have any spec that describes that this behavior is intended?
For now, the main point that I get from #24587 (comment) is that we forbid symbols as indexers because we have no symbol index signatures and for me it's sounds like bug in compiler because:
According to refs above consider following use case. I am implementing DI container where i would like to provide library users ability to use Symbols as keys(to avoid components collision) for their components. In my code I have something like:
interface ComponentsContainer { [key: PropertyKey]: Component; }Could someone provide strong argumentation why it's not a bug in compiler and this code shouldn't work?
fenying commentedon Aug 11, 2018
For the unbearable change, I gotta write a ugly line like:
What a stupid shit...
davalapar commentedon Feb 5, 2019
Can't believe that shit works.
Had to use
as unknown as stringthough since linter dislikes straight-upany.{ name: 'whatever', [Symbol(Item.Id)]: 'randomlygeneratedstring' }:-((( DIRTY HACK hotfix due to TS not supporting `symbol` as a type i…
evg656e commentedon Dec 17, 2019
Can't imagine how it could be marked as "work as intended", since we have this "TypeScript is a typed superset of JavaScript" on main page. This is definitely a bug in a type system and should be fixed somehow.
artalar commentedon Dec 21, 2019
Mohamed Hegazy (@mhegazy) why you labling it "Working as Intended"?
Please answer to the comment
slikts commentedon Dec 21, 2019
This issue seems mislabeled, but the main issue is #1863 and it's still open (and stalled apparently).
klesun commentedon Jul 31, 2021
Seems to be fixed by #44512 !
Available in
4.4.0-dev.20210627