My goal is to dynamically change the object type based on the value of the "key" attribute.
I have various types such as AElement
, BElement
, ..., ZElement
. Each element shares a common attribute called "name". Therefore, the type should be determined based on this attribute.
For instance:
// Elements
type AElement = {name:"a"; propA: string;}
type BElement = {name:"b"; propB: number;}
type CElement = {name:"c"; propC: string;}
// ...
type ZElement = {name:"z"; propZ: string; propZZ: number;}
// Map interface
interface ElementsMap {
"a": AElement;
"b": BElement;
"c": CElement;
//...
"z": ZElement
}
// Custom type
type Elem<K extends keyof ElementsMap = keyof ElementsMap> = ElementsMap[K];
// Usage
let elements:Elem[] = [{
name: "a",
propA: "123",
},{
name: "c",
propC: "321",
},{
name: "z",
propZ: "123",
propZZ: 123,
}];
// Test
let test1 = elements[2];
let test2: Elem = {
name: "a",
propA: "123",
}
When I use Element[]
, I expect each type to correspond to the key attribute "name" and utilize the specific props of that type. However, the variables test1 and test2 are currently of type:
AElement | BElement | CElement | ZElement
for each one, whereas I anticipate ZElement
and AElement
.