'type obj values by enum keys (TS)
I have an object with 2 types of values: str and num. I want to type all properties without duplicating of type name.
const obj: any = {
num1: number;
num2: number;
...
numN: number;
str1: string;
str2: string;
...
strN: string;
}
I expect to see the next results of types tests:
const obj: TObj = {
num1: 1, // ok
num2: '2', // error
str1: '1' // ok
str2: 2 // error
};
I think the answer lies next to the following pseudotype:
type TObj = {
[key in NumKeys]: number;
[key in StrKeys]: string;
};
UPD Partly, I achieved the goal by creating enums for iterating.
enum NumKeys {
num1 = 'num1',
num2 = 'num2',
...
numN = 'numN',
}
enum StrKeys {
str1 = 'str1',
str2 = 'str2',
...
strN = 'strN',
}
Then I created 2 temporary types for each of those.
type TNumObj = {
[key in NumKeys]: number;
};
type TStrObj = {
[key in StrKeys]: string;
};
Finally, I combined them to achieve the goal.
const obj: TNumObj & TStrObj = {
num1: 1,
num2: 2,
...
numN: N,
str1: '1',
str2: '2',
...
strN: 'N',
};
The annoying part of the answer is duplicating the same text in each key-value pair of the enum object.
enum NumKeys {
num1 = 'num1',
num2 = 'num2',
...
numN = 'numN',
}
Is there some simple way to create a such structure without duplicating?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
