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

Why doesn't it work with classes and interfaces? E.g.

interface Keywords {
    [P in NodeType]: string;
}

Typescript playground

DanielKucal avatar Mar 20 '17 15:03 DanielKucal

@mhegazy this doenst work for parameterized types either.

interface Component<Model, Action> {
  stateful: {
    init: () => Model,
    actions: {
      [Key in Action]: ({state}: {state: Model}, event: any) => Model
    }
  }
}

ccorcos avatar Mar 24 '17 21:03 ccorcos

Why doesn't it work with classes and interfaces? E.g.

Mapped types are only supported in type aliases. Interfaces and classes have merging semantics that do would not fit make much sense with mapped type.

mhegazy avatar Mar 24 '17 22:03 mhegazy

@ccorcos did you mean [Key in keyof Action] ?

Or is Action a string? if so then add a constraint for Action extends string.

mhegazy avatar Mar 24 '17 22:03 mhegazy

I tried this, but didn't work.

  type ItemName = "A" | "B" | "C";
  namespace ItemName {
    export const A: ItemName = "A";
    export const B: ItemName= "B";
    export const C: ItemName = "C";
  };

  const itemComments: {[name in ItemName]: string} = {
    [ItemName.A]: "Good",
    [ItemName.B]: "So-so",
    [ItemName.C]: "Bad",
  };

The error says:

[ts]
Type '{ [x: string]: string; }' is not assignable to type '{ A: string; B: string; C: string; }'.
  Property 'A' is missing in type '{ [x: string]: string; }'.

I think [ItemName.A] should be recognized as ItemName type, not a string.

masaori avatar Apr 13 '17 18:04 masaori

I think [ItemName.A] should be recognized as ItemName type, not a string.

This is the same issue tracked by https://github.com/Microsoft/TypeScript/issues/5579.

mhegazy avatar Apr 18 '17 00:04 mhegazy

@mhegazy If this doesn't work in interfaces, is there a different solution available, or a tracking issue for that case?

I'm trying to use this in some type definitions, and it doesn't support my case, using classes (or interfaces):

type ValidKey = "a" | "b" | "c";

declare class MyClass {
  [key: k in ValidKey]: string
}

I get "A parameter initializer is only allowed in a function or constructor implementation" (which isn't a particularly great error either, even given that this is unsupported).

pimterry avatar Jun 07 '17 10:06 pimterry

I found out that in order to make keys optional you can use Partial with this e.g.

type mapping = Partial<{ [k in "a" | "b"]: string }>

Small thing, but I struggled for a while with this.

P.S. I probably should read specs more closely, there is also a { [k in "a" | "b"] ? : string } for optional keys.

Ciantic avatar Jun 18 '17 16:06 Ciantic

It'd be great if this also worked for number literals:

{ [k in 1 | 2]: string }

Since this already works:

{ [k: number]: string }

leoasis avatar Jul 27 '17 15:07 leoasis

@leoasis I seem to recall that when mapped types were first introduced they did support other literals than strings, but that support was subsequently removed. I wonder why...

pelotom avatar Aug 05 '17 06:08 pelotom

Any update on this?

vinz243 avatar Mar 12 '18 11:03 vinz243

If I understand the thread correctly, is it not possible to parametrize a class by a type, then use the keys of that type in an index signature, like so:

class Form<T> {
    initialValues: {[fieldName: keyof T]: string} = {}
}

MaxGabriel avatar Mar 26 '18 23:03 MaxGabriel

@MaxGabriel Did you mean something like this?

class Form<T> {
  constructor(readonly initialValues: Partial<{ [field in keyof T]: string }> = {}) {}
}

karol-majewski avatar Mar 27 '18 12:03 karol-majewski

@karol-majewski Oh that works great! Thank you :)

MaxGabriel avatar Mar 27 '18 17:03 MaxGabriel

I came here when I ran into the error for enums. This is how I made it work:

export enum ThreeLetters {
  a = 'a',
  b = 'b',
  c = 'c'
}

const letterToName: {[key in ThreeLetters]: string} = {
  a: 'Ashok',
  b: 'Bobby',
  c: 'Clever'
}

ashok-sc avatar May 22 '18 21:05 ashok-sc

String literal types compatible with index signatures is one of the features I miss in TypeScript since a long time.

So often I define string literal enums in my project, such as:

type EmployeeType = "contractor" | "permanent";

or even list of geo, locale-related or money-related info, such as:

type Currency = "USD" | "GBP" | "EUR";

(whenever the number of items is fixed, not just a string).

Given a collection of items which include a property of above types, when reducing or grouping by that property, I expect to get:

{
  "contractor": ReducedValue...,
  "permanent": ReducedValue...
}

and I can't define the type as:

{ [type: EmployeeType]: ReducedType }

because it can be only a string or a number. So only thing I can do is to broaden it to a string, which is in fact to broad, since "other" is not a part of EmployeeType.

I wish this small feature lands in TypeScript one day :) not really sure why a string literal enum - being a subtype of string - is not allowed as an index signature (and string, the broader one, is).

ducin avatar Jun 06 '18 19:06 ducin

@ducin can you help me understand your use case better? The following seems to work as (I) expect:

type EmployeeType = "contractor" | "permanent";

const employees: { [employeeType in EmployeeType]: {} } = {
  "contractor": {}, // ok
  "permanent": {}, // ok
  "volunteer": {} // error
}

niedzielski avatar Jun 06 '18 20:06 niedzielski

@niedzielski I'm ashamed I never knew about this way to define an index signature. Thank you for this hint!

BTW why isn't { [type: employeeType]: {} } allowed (i.e. in is allowed and : isn't, what's the difference)?

ducin avatar Jun 06 '18 20:06 ducin

in makes a mapped type, while the other is an index signature. Mapped types are a little different in that they cannot have any properties other than the mapping operation (and can't be used in interfaces).

weswigham avatar Jun 06 '18 21:06 weswigham

@niedzielski What if I want any subset of string literal type be ok. Can I do this in 2018?

vehsakul avatar Jul 06 '18 19:07 vehsakul