TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

String literal types as index signature parameter types?

Open mariusschulz opened this issue 11 years ago • 73 comments

According to https://github.com/Microsoft/TypeScript/pull/5185, string literal types are assignable to plain strings. Given the following type definition:

type NodeType = "IfStatement"
              | "WhileStatement"
              | "ForStatement";

Both these assignments are valid:

const nodeType1: NodeType = "IfStatement";
const nodeType2: string = nodeType1;

However, string literal types currently can't be used as index signature parameter types. Therefore, the compiler complains about the following code:

let keywords: { [index: NodeType]: string } = {
    "IfStatement": "if",
    "WhileStatement": "while",
    "ForStatement": "for"
};

// error TS1023: An index signature parameter type must be 'string' or 'number'.

Shouldn't that scenario be supported, given that string literal types are assignable to strings?

/cc @DanielRosenwasser

mariusschulz avatar Nov 16 '15 14:11 mariusschulz

This issue is kind of the "dual" of #2491, and if we took this on we might want to reconsider that issue.

This is something that @weswigham has brought up a few times with me. One of the issues with this sort of thing is that undefined and null are possible values for each string literal type. This isn't something we consider to be a huge problem with numeric index signatures (they suffer from the same problem), but somehow I get a feeling like this is potentially more misleading. All in all, that doesn't seem to be a strong enough reason to dismiss it though.

DanielRosenwasser avatar Nov 17 '15 00:11 DanielRosenwasser

I'd like to argue from another perspective to point out why I think this feature is worth implementing. Consider the above NodeType type as found in a parser such as Esprima. String literal types are aimed at describing a set of finite possible string values, and listing all available statement/expression types of a parser is a perfect use case for that. If I'm forced to use plain strings as index signature parameter types, I lose the type safety that string literal types were made for to give me in the first place.

I agree, the issues are related. Let's see if we can find a solution here.

mariusschulz avatar Nov 17 '15 11:11 mariusschulz

For that sort of thing, you don't necessarily need a string literal index signature - an alternative approach is to just use the appropriate property name when indexing with string literal types. It's one of the open questions on #5185:

Given that we have the textual content of a string literal type, we could reasonably perform property lookups in an object. I think this is worthwhile to consider. This would be even more useful if we performed narrowing.

DanielRosenwasser avatar Nov 17 '15 18:11 DanielRosenwasser

Dup of #2491

jhlange avatar Dec 21 '15 08:12 jhlange

@jhlange I don't entirely think it is. While we are toying with the idea of unifying literal types with enums, this is somewhat distinct right now. If we do end up bringing them together, then #2491 will become much more relevant to the discussion.

DanielRosenwasser avatar Dec 21 '15 21:12 DanielRosenwasser

+1

ambition-consulting avatar Mar 11 '16 13:03 ambition-consulting

There's a highly relevant discussion on this at the exact duplicate issue #7656. I suggest checking out some of the information there.

malibuzios avatar Mar 23 '16 21:03 malibuzios

In order to truly implement something like this, the index signature parameter would first need to be type checked against the specialized type they are constrained to, e.g. { [key: number]: any } would reject a string or Symbol used as a key. Currently that in not enforced. Please see this comment in #7660 and participate in the discussion.

malibuzios avatar Mar 24 '16 08:03 malibuzios

This comment in #7660 is highly relevant to the topic here, though refers to the more general issue of how strictly should index signature keys be type-checked.

malibuzios avatar Mar 24 '16 11:03 malibuzios

+1

zakjan avatar Mar 30 '16 15:03 zakjan

@christyharagan posted some more motivating examples in #8336.

As @malibuzios points out, membersof (#7722) would be a nice feature to pair with this, but I think that should be considered orthogonal and not discussed here.

DanielRosenwasser avatar Jun 07 '16 05:06 DanielRosenwasser

Adding some more examples to what @mariusschulz was saying

describing a set of finite possible string values

The ability to enumerate the set of possible string values would be very useful. For example, given:

type DogName = "spike" | "brodie" | "buttercup";

interface DogMap {
  [index: DogName ]: Dog
}

let dogs: DogMap = { ... };

...it would be really nice to be able to do:

let dogNames: DogName[] = Object.keys(dogs);
// or
for (let dogName:DogName in dogs) {
  dogs[dogName].bark();
}

asakusuma avatar Jun 25 '16 00:06 asakusuma

Here is another example of how it would be nicer if we were able to use string literal types as index keys.

Consider this interface:

interface IPerson {
  getFullName(): string;
}

If your tests this, you might write something like this:

let person: IPerson = jasmine.createSpyObj('person', ['getFullName']);

or

let person = jasmine.createSpyObj<IPerson>('person', ['getFullName']);

but suppose you messed up and instead wrote this:

let person: IPerson = jasmine.createSpyObj('person', ['foo']);

Currently there is no way for TS to let you know there is a problem. But if the type definition could look something like this:

function createSpyObj<T extends string>(baseName: string, methodNames: T[]): {[key: T]: any};

then the inferred type could be something more like { 'foo': any } which would cause an error.

Now, I'm not sure right now if the compiler would infer the type of T as a string literal union type for something like this:

let person: IPerson = jasmine.createSpyObj('person', ['foo', 'bar']); //ERROR

Ideally there would be a way to help TS infer the generic T as 'foo' | 'bar' so that the inferred return type could be { 'foo': any; 'bar': any; }.

joeskeen avatar Jul 12 '16 16:07 joeskeen

+1

amarinov avatar Jul 18 '16 08:07 amarinov

Another use case: representing valid BCP47 language tags as keys for language maps, e.g.:

{
  "@context":
  {
    "occupation": { "@id": "ex:occupation", "@container": "@language" }
  },
  "name": "Yagyū Muneyoshi",
  "occupation":
  {
    "ja": "忍者",
    "en": "Ninja",
    "cs": "Nindža"
  }
}

This would be difficult to represent, however, because there are so many valid language tags. They are not limited just the two-letter identifiers, but rather they can include things like region, e.g.:

  {
    "en-US": "elevator",
    "en-GB": "lift"
  }

ariutta avatar Sep 26 '16 18:09 ariutta

Flow has this feature and it's quite nice to have.

pelotom avatar Oct 19 '16 05:10 pelotom

Here's another use case: the typing of underscore's mapObject function would ideally maintain knowledge about the set of possible keys, so that:

// foo conforms to type { [key: 'x'|'y']: string }
const foo = {
  x: 'hello',
  y: 'world',
}

// type of bar is inferred to be { [key: 'x'|'y']: number }
const bar = mapObject(foo, s => s.length)

pelotom avatar Oct 31 '16 02:10 pelotom

Another usage, string literal key as constraints of object.

function prop<K extends string>(name: K): <S extends { [K]: any }>(s: S) => S[K] {
    return s => s[name];
}

prop('myProp')({myProp: 123})

This pattern is heavily used in functional library like rambda.

More generally, string literal key enables dynamic type building.

HerringtonDarkholme avatar Nov 04 '16 02:11 HerringtonDarkholme

Use of literal types (and more especially, generic type parameters constrained to literal types) provides a strict superset of the functionality provided in #11929. Notably:

function get<T, K extends keyof T>(obj: T, name: K): T[K] {
    return obj[name];
}
function set<T, K extends keyof T>(obj: T, name: K, value: T[K]): void {
    obj[name] = value;
}

is equivalent to, though definitely neater than:

function get<K extends (string | number), V, K1 extends K>(obj: { [key: K]: V }, name: K1): V {
    return obj[name];
}
function set<K extends (string | number), V, K1 extends K, V1 extends V>(obj: { [key: K]: V }, name: K1, value: V1): void {
    obj[name] = value;
}

Note that the additional type parameters K1 extends K, V1 extends V are necessary due to the fact that generic type parameter inference cannot be selectively disabled, so without them K and V would eventually fall back to (string | number if not {}) and ({} or any), respectively.

PyroVortex avatar Nov 05 '16 03:11 PyroVortex

This should be possible now using Mapped types

So you can write the example in the original example as:


type NodeType = "IfStatement"
              | "WhileStatement"
              | "ForStatement";

let keywords: {[P in NodeType]: string };

keywords = {
      "IfStatement": "if",
      "WhileStatement": "while",
      "ForStatement": "for"
};  // OK

keywords.ifStatement; // OK


keywords = {  "another": "wrong" } // Error

mhegazy avatar Nov 14 '16 19:11 mhegazy