TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

'type' aliases of string can not be used as object index signature.

Open jlennox opened this issue 11 years ago • 60 comments

type Guid = string;
var foo: { [deviceId: Guid]: DateTime } = {};

Generates the error:

An index signature parameter type must be 'string' or 'number'.

It would be nice to be able to type indexes using string-aliases.

jlennox avatar Jan 23 '15 01:01 jlennox

Can we get some input from maintainers on this? It's sorely missed and difficult to find an open source solution without it.

noahbjohnson avatar Jan 22 '20 15:01 noahbjohnson

I cry every time I hit this arbitrary limitation.

Also see https://github.com/microsoft/TypeScript/issues/15746 which got closed.

AlexGalays avatar Feb 05 '20 14:02 AlexGalays

All the prior input we've provided is still true

RyanCavanaugh avatar Feb 05 '20 16:02 RyanCavanaugh

@RyanCavanaugh The last input you provided was to use mock Hungarian notation.

People have provided a lot of substantive feedback that has been unaddressed. Since I'd just be repeating other people's points, see https://github.com/microsoft/TypeScript/issues/1778#issuecomment-544150040

jlennox avatar Feb 05 '20 17:02 jlennox

Branded strings are about the only reason I can see for this. And there's a workaround for branded strings as keys, even if not the best experience.

AnyhowStep avatar Feb 05 '20 18:02 AnyhowStep

I don't know what I can do that will make people happy except to implement a feature we think is a bad idea. We've read the feedback, we understand it, we see why people might want it, but we think the feature is a bad idea to add to the language at this time and are thus choosing not to do so. Someone not agreeing with you is not the same as them not listening to you.

It all boils down to:

This falls under the category of not appearing to do something you don't.

We think allowing you to write type aliases here creates the implication that you're making different kinds of index signature, but you're not. It's actively confusing and doesn't create any new functionality. Why would we add new syntax for doing something you can already do with perfect clarity? It's harmful.

RyanCavanaugh avatar Feb 05 '20 18:02 RyanCavanaugh

@RyanCavanaugh

It's actively confusing and doesn't create any new functionality.

IMO that's false, in that if you can limit keys to a particular set of strings, you can do union types in which the types aren't in conflict. e.g. if you do [key: string]: number then all other keys / types must conform to a number. But if you do [key: Foo]: number, then ONLY keys conforming to Foo must be a type of number (or a compatible type such as any).

AFAIK, there's no way to specify "defined keys are these types, any extra keys are of this specific type" using current syntax. A simple solution would be to limit extra keys to a specific set of strings.

matthew-dean avatar Feb 05 '20 20:02 matthew-dean

Is there any other place where type aliases can't be used? That is what has always confused me. This has never seemed like a new feature but a missing application of the existing feature: type aliases. The very first line of the code example for type aliases in the handbook is an example of branded strings (https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-aliases), so there's no indication that their use is discouraged. Of anywhere, branded strings for index signatures is the place where that makes the most sense to expect that people will careful about whether they are really just strings, rather than aliases used in function signatures or property types. Why is there less concern about people expecting compile-time safety with branded strings when used anywhere else?

I'm honestly looking for an example. I've been curious about this while getting periodic notifications on this issue over the last 5 years. I can't think of a reason for type aliases not to be usable in 100% of the same places as regular types.

aelr avatar Feb 06 '20 00:02 aelr

@matthew-dean But this issue is ONLY about allowing an alias instead of string (or presumably number). Is specifically not about allowing index signatures with unions.

Allowing unions would be a different matter and is the subject of this (presumably on the back burner) PR #26797. Without the abilities in #26797 I don't think allowing aliases in that position really brings much value.

dragomirtitian avatar Feb 12 '20 11:02 dragomirtitian

I've returned to this issue because I've run into this problem again and again and it's driving me nuts.

@RyanCavanaugh

It's actively confusing and doesn't create any new functionality.

Whether it's confusing is a matter of opinion (I personally don't see how this would be any more confusing than the existing myriad of TypeScript functionalities), but it absolutely does lend a clear and useful function that to this day is sorely missing. Especially in a language like Javascript where it's common to fire up objects and use them as key-value maps.

public repeatableSections: { [s: string]: TemplateElement } = {};
public sectionHashMap: { [s: string]: TemplateElement } = {};
public fieldsThatHaveCrossElementChildren: { [s: string]: FormField } = {};
public elementHashMap: { [s: string]: FormElement } = {};

I have plenty of the above in my application. I use hashmap-like structures for performance and caching reasons. Each of those string indexes correspond to a particular property of another interface which I populate during initialization. I have no way of clearly indicating and tracing where those indexes would originate from. Other than having to write a clumsy comment which serves to bloat the code, or just having to remember what's going on.

public repeatableSections: { [ s: SomeInterface['someStringProperty'] ]: TemplateElement } = {};
public sectionHashMap: { [ s: SomeInterface['someStringProperty'] ]: TemplateElement } = {};
public fieldsThatHaveCrossElementChildren: { [ s: SomeInterface['someStringProperty'] ]: FormField } = {};
public elementHashMap: { [ s: SomeInterface['someStringProperty'] ]: FormElement } = {};

Notice how that is self-documenting, and how it objectively reduces confusion in this case by providing context? A person reading that not only understands that the index derives from a particular data structure, but they enjoy the fast-travel functionality in VSCode to speed up their workflow.

Why bring types to a language if you're not going to properly leverage them?

jpike88 avatar Feb 14 '20 18:02 jpike88

For what it's worth, I've started writing object key name and key type backwards. Obviously this is not safe if the definitions change but at least it let's you document the intended type of the key.

type CustomerId = string;
type Customer = {
  id: CustomerId;
  name: string;
};
type CustomerRecord = { [CustomerId: string]: Customer };

cyberixae avatar Feb 15 '20 14:02 cyberixae

From the TS documentation:

Aliasing doesn’t actually create a new type - it creates a new name to refer to that type. Aliasing a primitive is not terribly useful, though it can be used as a form of documentation.

From the argument here:

We think allowing you to write type aliases here creates the implication that you're making different kinds of index signature, but you're not. It's actively confusing and doesn't create any new functionality. Why would we add new syntax for doing something you can already do with perfect clarity?

I'm getting very mixed messages here. Why offer type aliases at all, then? Either you accept they're a part of the language and their rules are implemented unilaterally throughout the language (that is, accept that type aliases are a feature), or you don't.

The minute you do a bit of both is the minute you add a bunch of minefields to your software, minefields where I need to go, yet again, "why isn't this rational thing I'd expect would work in TS not work for me in this instance but does in this instance?"

gravitypersists avatar Feb 21 '20 18:02 gravitypersists

The minute you do a bit of both is the minute you add a bunch of minefields to your software, minefields where I need to go, yet again, "why isn't this rational thing I'd expect would work in TS not work for me in this instance but does in this instance?"

This +1000. Either types can be aliased or they can't. Either 'foo' | 'bar' are a limited set of strings or they aren't. This weird thing we got here where it's like "the key is assigned a type, except it isn't, because string isn't a type the way types are types" is contrary to the rest of the language.

matthew-dean avatar Feb 21 '20 19:02 matthew-dean

@RyanCavanaugh this is an issue of ergonomics and there is clearly an issue. What do you propose to offset the workarounds we’ve been doing?

jpike88 avatar Feb 22 '20 02:02 jpike88

@RyanCavanaugh I request that this issue is reopened, because I’m still running into this issue, you haven’t suggested any workarounds to this issue, and have offered a rather unconvincing justification that seems to be skirting the reality of the problem.

Please clearly read this:

https://github.com/microsoft/TypeScript/issues/1778#issuecomment-586419491

And tell me how I’m supposed to be handling this scenario beyond an argument like ‘you’re holding it wrong’.

I know I’m not writing your paycheck but this is clearly an ongoing issue and I get the impression your team is sweeping it under the rug favouring semantics over actual developer concerns, and this is becoming immensely frustrating to read.

Please at least do me the service of responding to what is being said here. If I (among others) are just shouting into the wind, let us know your decision is final and not for any more debate, and I will divest myself and move on.

jpike88 avatar Feb 29 '20 17:02 jpike88

Due to unresponsiveness on this issue, I'm raising another one:

https://github.com/microsoft/TypeScript/issues/37448

jpike88 avatar Mar 18 '20 08:03 jpike88

I was also trying to use this as self-documenting code and found I couldn't. As others, I had to introduce awkward comments to describe what the key is, instead. Not ideal.

phoenixeliot avatar Apr 07 '21 23:04 phoenixeliot

As a complete surprise, this just started working.

type CellId = string;
type Row = {[cellId: CellId]: string}; // \o/
const row: Row = {'cell1': 'a'}

Digging deeper, the new index signature features are in the 4.4 release notes.

jamesgpearce avatar Sep 05 '21 18:09 jamesgpearce

For me it was a surprise that it doesn't work in the old versions of the TS. To support old TS versions I had to change my Guid type alias to string. Many thanks to all those people who requested this feature for so many years! It's a win! :)

sergii-zhuravel avatar Sep 21 '21 07:09 sergii-zhuravel

If you're using an older version of Typescript I have had success with a mapped object type instead.

Arbitrary example, not tested, but should work with at least 4.2.4:

export type PersonName = string;
interface Person {
  name: string;
};

type NameToPerson = {
  [personName in PersonName]: Person;
};

acdoussan avatar Apr 07 '23 16:04 acdoussan