String literal types as index signature parameter types?
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
Why doesn't it work with classes and interfaces? E.g.
interface Keywords {
[P in NodeType]: string;
}
@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
}
}
}
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.
@ccorcos did you mean [Key in keyof Action] ?
Or is Action a string? if so then add a constraint for Action extends string.
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.
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 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).
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.
It'd be great if this also worked for number literals:
{ [k in 1 | 2]: string }
Since this already works:
{ [k: number]: string }
@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...
Any update on this?
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 Did you mean something like this?
class Form<T> {
constructor(readonly initialValues: Partial<{ [field in keyof T]: string }> = {}) {}
}
@karol-majewski Oh that works great! Thank you :)
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'
}
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 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 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)?
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).
@niedzielski What if I want any subset of string literal type be ok. Can I do this in 2018?