Created
May 3, 2021 22:14
-
-
Save d9k/a0cd3d968de7604b809fa1acf4c07331 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://stackoverflow.com/questions/67341992/constructor-with-return-generic-type-based-on-param-enum-ts2322/67376400#67376400 | |
enum Enum { | |
one = 'one', | |
two = 'two', | |
} | |
type Type1 = { | |
field: typeof Enum.one; | |
anotherField: number; | |
}; | |
type Type2 = { | |
field: typeof Enum.two; | |
someAnotherField: number; | |
}; | |
type TypeN = Type1 | Type2; | |
type ConstructorN<T> = () => Extract< | |
TypeN, | |
{ | |
field: T; | |
} | |
>; | |
type Constructors = { | |
[T in Enum]: ConstructorN<T>; | |
}; | |
let constructors: Constructors = { | |
[Enum.one]: () => { | |
let obj: Type1 = { | |
field: Enum.one, | |
anotherField: 1, | |
}; | |
return obj; | |
}, | |
[Enum.two]: () => { | |
let obj: Type2 = { | |
field: Enum.two, | |
someAnotherField: 2, | |
}; | |
return obj; | |
}, | |
}; | |
console.log(constructors[Enum.one]()) | |
// { field: 'one', anotherField: 1 } | |
console.log(constructors[Enum.two]()) | |
// { field: 'two', someAnotherField: 2 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment