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

jfc, i was just talking about your example with Currency and Money, didn't say or mean it can/should be used anywhere

zpdDG4gta8XKpMCd avatar Jan 06 '19 14:01 zpdDG4gta8XKpMCd

@RyanCavanaugh could this be revisited and could there be a proper discussion on the topic? I feel like the amount of people voting for this feature proposal are in the majority and no chance has been given to us to express why we'd want this. Even if there is no enforcement yet, is there any chance for limited support for this and not errors generated by the compiler. Because in your own words:

Specifically, all type aliases of a type are equivalent, so you could still index foo by a CustomerName.

Then why is it disallowed? What would in your opinion be the downsides of still implementing this behaviour? Does it outweigh the features it offers? Are these restrictions of Javascript even possible to be worked around? And if not, shouldn't we accept these restrictions and still move forward with these limited features?

AndreasBackx avatar Jan 23 '19 14:01 AndreasBackx

I feel like the amount of people voting for this feature proposal are in the majority and no chance has been given to us to express why we'd want this

You wrote this comment and I'm reading it, same as we read all the other comments. What specific behavior are you looking for from us to make you feel that your opinion is able to be expressed (in the context that we do still believe this isn't a good fit for the language)?

Does it outweigh the features it offers?

It doesn't offer any features at all - that's the problem!

RyanCavanaugh avatar Jan 23 '19 17:01 RyanCavanaugh

There's already a place to write the intended index semantics (deviceId should probably be deviceGuid ?).

This isn't very convincing because it feels like arguing for Hungarian notation.

It seems rational that indexes wouldn't be compiler enforced because anything type aliased isn't enforced. That is, my original example with Guid is as strongly typed as this follow valid code is:

type SomeNewType = string;

function someFunction(ourNewType: SomeNewType) { }

someFunction("This is of string type.");

I see no reason that this permits a string to be passed to someFunction, but SomeNewType can't be used as an index.

jlennox avatar Jan 23 '19 17:01 jlennox

I want to lend my support for this feature as well. My company has a lot of interfaces representing domain objects that are loaded in from the backend. Sometimes we need to create other data structures that use the data from those domain objects in various ways, including as the keys of objects. Here's a somewhat silly example: an object in which the keys are student IDs and the value is the status of the student's homework.

type studentHomeworkStatuses = {
  // the index is a student ID
  [index: number]: 'incomplete' | 'finished' | 'graded';
}

It would be really nice to be able to rewrite this without the comment and leverage the student interface we already have:

interface Student = {
  id: number;
  ...other properties
}

type studentHomeworkStatuses = {
  [index: Student['id']]: 'incomplete' | 'finished' | 'graded';
}

Why is this better?

  • We've built the documentation into our code, instead of having to write an extra comment to explain it.
  • We can more easily change the type of a Student['id'] from a number to a string in the future (if for some reason that becomes necessary), and have the type update throughout our codebase.

@RyanCavanaugh What do you (and other TS folk) think about these two benefits?

nwshane avatar Feb 19 '19 16:02 nwshane

@RyanCavanaugh @nwshane this is a huge issue for us too but I've been writing FooDict objects and hiding the underlying storage with a toKey() mechanism. It's definitely not perfect but better than having to expose the ugliness to outside callers.

InputNeuron avatar Feb 20 '19 20:02 InputNeuron

@burtonator I'm not sure I understand—can you give an example of how you're doing that?

nwshane avatar Feb 20 '19 20:02 nwshane

it's just a facade hiding the ugly /internal data structure.

class CarDict {

   private backing: {[id: string]: Accidents} = {};

  private string toKey(car: Car) {
    return car.name;
  }
  
  public get(car: Car): Accidents {
     return this.backing[this.toKey(car)];
  }
  public set(car: Car, accidents: Accidents) {
    this.backing[this.toKey(car)] = accidents;
  } 
}

you could also make it extend an abstract interface using generics and then force the new class to implement toKey

... and this code is a big ugly as it's just an example.

InputNeuron avatar Feb 20 '19 21:02 InputNeuron

Like @niedzielski mentionde, the following syntax

type NumberAlias = number
type Foo = {[K in NumberAlias}: any}

actually works, and Foo gets resolved to {[x: number]: any} as expected! I also believe this is just a happenstance of how mapped types work, since {[K in number}: any} is also valid. However, doesn't mean we can't use it! :wink:

ethernet8023 avatar Apr 04 '19 17:04 ethernet8023

Like @niedzielski mentionde, the following syntax

type NumberAlias = number
type Foo = {[K in NumberAlias}: any}

actually works, and Foo gets resolved to {[x: number]: any} as expected! I also believe this is just a happenstance of how mapped types work, since {[K in number}: any} is also valid. However, doesn't mean we can't use it! 😉

This won't work for interfaces though.

ps. You have some typo's I think; using a curly brace instead of square bracket for closing.

alowaniak avatar Jun 25 '19 07:06 alowaniak

@nwshane It works :smile:

You just have to use in in the declaration of the index signature:

interface Student {
  id: number;
  // ...other properties
}

type studentHomeworkStatuses = {
  [index in Student['id']]: 'incomplete' | 'finished' | 'graded';
}

const hws: studentHomeworkStatuses = {
    1254815515: "finished",
    7841818115: "graded",
    7841518113: "graded",
}

It even gives you code completition See here

neryortez avatar Jul 10 '19 07:07 neryortez

I don't get it, there's a clear benefit here.

It doesn't offer any features at all - that's the problem!

@RyanCavanaugh The feature is that context can be given to what that index is supposed to be used for. To me it seems arbitrary to prevent this from happening, you're restricting the amount of self-documenting code that can be written, with zero apparent drawbacks.

People are now coming up with weird workarounds to emulate this, so it has a clear need.

Restricting the type alias to allow only certain primitives is a perfectly fine caveat.

Maps allow generics to both provide type safety and improve code readability, why wouldn't you treat index signatures with the same amount of consideration?

I'd ask that this is reopened and given a proper look. Look at the votes.

jpike88 avatar Sep 17 '19 06:09 jpike88

I agree with @jpike88 ... for me the main use case is 'typed' string. I often have strings like URLStr, RegexStr, PathStr, etc. Each is a strict subset of all strings. URLStr is a URL for example.

it's MUCH clearer to have a map of URLStr as a key or PathStr as a key.

I guess I can name the key 'path' but that take away a bit of semantics because with PathStr I can jump to that declaration and read the semantics of PathStr

InputNeuron avatar Sep 17 '19 19:09 InputNeuron

Another reason for this is to define keys as not belonging to other keys, like:

type Foo = {
  known1: string
  known2: string
}
type Bar = {
  [key: keysNotInFoo]: number
}
type FooBar = Foo & Bar

The only way there appears to do this now is some kind of really complex union types like: the answer in this Stack Overflow post: https://stackoverflow.com/questions/49969390/how-do-i-type-an-object-with-known-and-unknown-keys-in-typescript/57993115#57993115

matthew-dean avatar Sep 18 '19 14:09 matthew-dean

I would also like to add my support for this feature. The arguments seem to be that this doesn't add any features, and there doesn't seem to be any reason to type alias to primitives because it makes no different to compiler. However given that there already is support for type aliasing primitives, it seems like there should be consistency as to where these aliases could be used. Type aliases for strings can and are used to make code far more self documenting, take the (exaggerated) example:

type AlphaId = string;
type Alpha = { [key: AlphaId]: { ... } }

type BravoId = string;
type Bravo = { [key: BravoId]: { ... } };

type CharlieId = string;
type Charlie = { [key: CharlieId]: { ... } };

type State = {
    alpha: AlphaId;
    bravo: BravoId;
    charlie: CharlieId;
};

vs

type Alpha = { [key: string]: { ... } }

type Bravo = { [key: string]: { ... } };

type Charlie = { [key: string]: { ... } };

type State = {
    alpha: string;
    bravo: string;
    charlie: string;
};

I think there's a stark difference between the clarity of typing, despite both being equal at compile time. Ironically, TS currently allows for an "in-between" solution, where you can type alias to strings but can't use those type aliases to define key types.

nick-michael avatar Oct 19 '19 11:10 nick-michael

I'll respectfully ask the Typescript team to give this issue attention instead of ignoring users.

@orta, @DanielRosenwasser, @rbuckton, @sandersn, @sheetalkamat, @RyanCavanaugh

I'm cc'ing in recent contributors.

Please read this issue carefully and consider the facts:

  • strong arguments were made for implementing this feature across a range of use cases
  • a single weak justification was given for ignoring this feature, which was immediately rebutted
  • the justification has been downvoted heavily by users of Typescript
  • this feature has been closed anyway

I'd like due diligence to be applied to this feature. It's a no brainer. There is a clear need for it, with no design pattern or workaround to compensate.

jpike88 avatar Oct 19 '19 14:10 jpike88

Just to give another real life example, where TypeScript fails to type a JS object, I'm using this pattern often in the next version of Less (simplified for this example).

type Props = { 
  value: string | number
  text: string
}

type IProps = Props & { [key: ?(not defined keys in Props)]: Node[] } 

//...
constructor(props: IProps) {
  // The API here is that any key not explicitly defined is
  // an arbitrary node collection
  // The following deconstruction is very common in JS, but
  // TypeScript currently has no way to strongly type `children`, if the keys
  // can be any string value
  const { value, text, ...children } = props
// ...
}

My workaround is essentially to do [key: string]: any in order to not cause conflict with the existing keys, but of course that's a hack because I know the types; they're very explicitly defined in JS, but cannot be defined in TS, because the type provided by [key: string] has to intersect with the types of defined keys. The fact that ...rest objects can't be strongly typed in TypeScript is just an odd hole in the syntax (unless there's a workaround I haven't found yet?)

matthew-dean avatar Oct 19 '19 19:10 matthew-dean

I'm hitting the same problem in JXA (JavaScript for Automation, in macOS), when a collection is of named objects. Consider,

// This gets the Finder window with the name "Documents".
Application("Finder").windows.byName('Documents');

// This does the same thing.
Application("Finder").windows['Documents'];

// So does this, for the record, although it's not how the API is expected to be used.
Application("Finder").windows.Documents;

In other words, Application("Finder").windows is an object where every string key is a Window, except specifically for byName—and similarly byId and at—which are all functions. There appears to be no way to type this object in TypeScript.

Peeja avatar Dec 03 '19 00:12 Peeja

I was playing around with branded strings for extra type safety. I've never played with branded types much before.

Then, I noticed this annoying thing,

type MyKey = string & { someBrand: void };
type MyMap = Record<MyKey, number>;

declare const myMap: MyMap;
//const myKey: MyKey
declare const myKey: keyof MyMap;

/*
    Expected: OK
    
    Actual  :
    Element implicitly has an 'any' type because
    expression of type 'MyKey'
    can't be used to index type 'Record<MyKey, number>'
*/
console.log(myMap[myKey]);

So, I made a workaround,


function getWorkaround<K extends PropertyKey, V>(record : Record<K, V>, key : K) : V {
    return record[key];
}
/*
    Expected: OK
    Actual  : OK
*/
getWorkaround(myMap, myKey);

Playground

I really wish branded strings could be used to index objects. But I'll take this workaround.


[Edit]

You might need to change the parameter to Readonly<Record<K, V>>, if you're working with readonly records.

AnyhowStep avatar Dec 29 '19 09:12 AnyhowStep

Seems like a legit requirement. Flow handles this just fine.

jamesgpearce avatar Jan 06 '20 04:01 jamesgpearce