I have a TypeScript code snippet in the playground. Please take a look there at TypeScript playground or here:
enum MyTypes {
FIRST = "FIRST",
SECOND = "SECOND",
THIRD = "THIRD"
}
type TFirst = {
type: MyTypes.FIRST
foo: string
}
type TSecond = {
type: MyTypes.SECOND
foo: string
}
type TThird = {
type: MyTypes.THIRD
bar: string
}
type TConditionalType<T> =
T extends MyTypes.FIRST ? TFirst :
T extends MyTypes.SECOND ? TSecond :
T extends MyTypes.THIRD ? TThird :
null
const getMyObjectBasedOnType = <T extends MyTypes>(type: T): TConditionalType<T> | null => {
switch (type) {
case MyTypes.FIRST: {
return {
type: MyTypes.FIRST,
foo: 'test'
}
}
default: {
return null
}
}
}
const firstObject = getMyObjectBasedOnType(MyTypes.FIRST)
// firstObject is type of TFirst or null which is okay
if (firstObject) {
firstObject.foo
}
There is a function getMyObjectBasedOnType(type: T)
which returns an object of a conditional type based on the type
parameter. This seems to work since firstObject
at the end is of type TFirst | null
. All clear here.
Problem which I have is TypeScript error inside mentioned function on line 31 when I am returning object. I get this:
Type '{ type: MyTypes.FIRST; foo: string; }' is not assignable to type 'TConditionalType<T>'.
I can't figure it out what is wrong. As far as I understand it that is an object of TFirst
which should be okay. Why do I receive this error and what is proper fix for it?