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
@vehsakul You mean like this?
type MyStringLiteral =
| "a"
| "b"
| "c";
const asRecordType: Partial<Record<MyStringLiteral, any>> = {
b: 1,
}
const asMappedType: { [property in MyStringLiteral]?: any } = {
b: 1,
}
@karol-majewski Yes, exactly. Thanks. Dropped out from TS world for a while. Now ask dumb questions :)
Not sure if I'm missing something here, but I would've expected this to work.
type Department = "finance" | "engineering" | "marketing";
type DepartmentMap<TValue> = { [P in Department]: TValue };
let employeesByDepartment: DepartmentMap<string[]> = {
"finance": ["Karen", "Jack"],
"engineering": ["Natalie", "Matt"],
"marketing": ["Michael", "Sally"]
};
for (let department in employeesByDepartment) {
// Type of department is string, so:
// Why am I allowed to use it as an indexer on line 13? Shouldn't I only be allowed to index with a Department?
// Why is it not of type Department?
let employees: string[] = employeesByDepartment[department];
assignDepartmentInPayroll(department, employees); // this line does not compile
}
function assignDepartmentInPayroll(department: Department, employees: string[]) {
// do something
}
I have a feeling there's a right way to do this, but I can't seem to find it.
@MRayermannMSFT Type assertion (department as Department, employees) does the job.
In my opinion above code is semantically correct, just the for..in is unable to narrow down the type of the key to a string literal enum. Such internal incompatibilities in TypeScript do appear, unfortunately. Maybe such issue could be easily improved, @mhegazy ?
See https://github.com/Microsoft/TypeScript/pull/12253#issuecomment-263132208 for why department can't be inferred to have type Department. Having exact types might solve the problem?
Yep that would explain the reason why the type is not inferred. I'll look into exact types, @ducin , Yes, I could use as to get the property type, but to me that's not the ideal solution. Thank you for the suggestion though, as it is what I'll probably have to go with. 😄
A related question, I wonder why: Given:
type NodeType = "IfStatement"
| "WhileStatement"
| "ForStatement";
The code below works:
type GoodStuff = {[P in NodeType]?: string } // Note that value type is set to "string"
let keywords: GoodStuff = {
IfStatement: "if",
WhileStatement: "while",
another: "another", // This triggers error as expected
};
But this doesn't:
type GoodStuff = {[P in NodeType]?: NodeType } // Note that value type is set to "NodeType"
let keywords: GoodStuff = {
IfStatement: "if",
WhileStatement: "while",
another: "another", // This no longer triggers error :(
};
@benjamin21st It does seem to work correctly. See TypeScript playground with TypeScript 3.0.1 installed.
@karol-majewski Ah~ Thanks! Then I'll just have to convince my team to upgrade to 3.0 :joy:
If you have an enum (indexed by numbers), but you want your object to have string keys, here’s my solution:
enum NodeEnum {
IfStatement,
WhileStatement,
ForStatement,
}
const keywords: { [index in keyof typeof NodeEnum]: string } = {
"IfStatement": "if",
"WhileStatement": "while",
"ForStatement": "for",
}
Actually you can write this like the following:
enum Color {
red,
green,
blue
}
type ColorMap<C extends object, T> = { [P in keyof C]: T };
const colors: ColorMap<typeof Color, string> = {
red: 'red',
green: 'green',
blue: 'blue'
};
Boom type checking!
Actually you can write this like the following:
enum Color { red, green, blue } type ColorMap<C extends object, T> = { [P in keyof C]: T }; const colors: ColorMap<typeof Color, string> = { red: 'red', green: 'green', blue: 'blue' };Boom type checking!
Thanks!!! This is AWESOME!!!
enum Color { red, green, blue } type ColorMap<C extends object, T> = { [P in keyof C]: T }; const colors: ColorMap<typeof Color, string> = { red: 'red', green: 'green', blue: 'blue' };
Not really, if you change your colors to be:
const colors: ColorMap<typeof Color, string> = {
red: 'green', // <------- We don't expect this, do we?
green: 'green',
blue: 'blue'
};
Same situation
type Method = 'get' | 'post' | 'put' | 'delete'
const methods: Method[] = ['get', 'post', 'put', 'delete']
class Api {
[method in Method]: Function // <-- Error here
constructor() {
methods.forEach(method => {
this[method] = (options: any) => { this.send({ ...options, method }) }
})
}
send(options:any) {
// ....
}
}
How should i handle this case ?
For Googlers and others
What you want (and does NOT work):
type Ma = { [key: 'Foo']: number }
type Mb = { [key: 'Foo' | 'Bar']: number }
type Mc = { [key: 'Foo' | 'Bar' | 0.3]: number }
// etc
What you need (and does work):
type Ma = { [key in 'Foo']?: number }
type Mb = { [key in 'Foo' | 'Bar']?: number }
type Mc = { [key in 'Foo' | 'Bar' | 0.3]?: number }
const x: Ma = {}
const y: Ma = { 'Foo': 1 }
const z: Mc = { [0.3]: 1 }
// const w: Ma = { 'boop': 1 } // error
Unfortunate constraints: Example 1
type Mx = {
Bar: number // OK, but has to be a number type
[key: string]: number
}
Example 2
type My = {
Bar: number, // Error, because of below
[key in 'Foo']: number
}
Is it possible to achieve something like this:
// TPropertyName must be a string
export type Foo<TPropertyName = "propertyName"> = {
[key in TPropertyName]: number
};
@n1ru4l You need to set a constraint on TPropertyName:
export type Foo<TPropertyName extends string = "propertyName"> = {
[key in TPropertyName]: number
};
Ok, with all these solutions proposed, it seems there is still none piece of the puzzle missing; iterating over an object's keys:
declare enum State {
sleep,
idle,
busy,
}
type States = { [S in keyof typeof State]: number };
const states: States = {
sleep: 0x00,
idle: 0x02,
busy: 0x03,
};
function getNameFromValue(state: number): State | undefined {
for (const k in states){
if (states[k] === state) {
return k; // type string !== type State and cannot be typecasted
}
}
}
The solution @dcousens proposed doesn't really help because my State enum is actually 20 lines of code and I don't think anyone would want that in their project.
@LukasBombach What do you want getNameFromValue to return — the name of one of the keys or the numeric value on the right-hand side of your enum?
Staterefers to the value of an enum,typeof Statewould be the type of your enum (here: an object),keyof typeof Stateis the key of your enum.
If your enum looks like this:
enum State {
sleep = 0x00,
idle = 0x02,
busy = 0x03,
}
Then you can get the key by doing:
function getNameFromValue(state: number): keyof typeof State | undefined {
return State[state] as keyof typeof State | undefined;
}
and the value by doing:
function getNameFromValue(state: number): State | undefined {
for (const k of UNSAFE_values(State)) {
if (state === k) {
return k
}
}
return undefined;
}
const UNSAFE_values = <T extends object>(source: T): T[keyof T][] =>
Object.values(source) as T[keyof T][];
@karol-majewski thank you! What I want to return is the String that is restricted to specific values, I managed to do it the way I do it up there. The way I understand your solution, it is similar to mine but the keys and values / the access to it is reversed.
What bugs me is that I have to do a type cast, which I'd like to avoid.