Last active
October 6, 2021 16:32
-
-
Save joemaidman/cbc38b1f6474532d616b53f46c58274b to your computer and use it in GitHub Desktop.
Type issue
This file contains 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
// using TS V3.7.5 | |
type ClassType<T> = new () => T; | |
class DefaultClass {} | |
class RedClass {} | |
class OrangeClass {} | |
class GreenClass {} | |
const enum MyEnum { | |
RED = 'RED', | |
ORANGE = 'ORANGE', | |
GREEN = 'GREEN', | |
} | |
const getColour = (): MyEnum => { | |
// just an example, could be any of the enum values (in reality comes from a request) | |
return MyEnum.GREEN; | |
}; | |
const myFunction = <T, S>(defaultClassType: ClassType<T>, overrides: { colour: MyEnum; classType: ClassType<S> }[]) => { | |
const colour = getColour(); | |
const colourOverride = overrides.find(or => or.colour === colour); | |
if (colourOverride) { | |
return new colourOverride.classType(); | |
} else { | |
return new defaultClassType(); | |
} | |
}; | |
// Query: this infers the type of instance as 'DefaultClass | GreenClass' but we want it to be 'DefaultClass | RedClass | OrangeClass | GreenClass' | |
const instance = myFunction(DefaultClass, [ | |
{ colour: MyEnum.RED, classType: RedClass }, | |
{ colour: MyEnum.ORANGE, classType: OrangeClass }, | |
{ colour: MyEnum.GREEN, classType: GreenClass }, | |
]); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment