When working with a function that takes an object of either TypeA or TypeB, the first parameter is used to specify the type of the object and the returned type depends on this first parameter.
The issue arises in TypeScript where the type of the object is not inferred within a case (or if) statement, resulting in errors in the following code.
If you're like me and prefer to avoid explicit casting (such as adding as TypeA
), are there any alternative solutions available?
type TypeA = {
input: { foo: string }
output: { foo: number }
}
type TypeB = {
input: { bar: string }
output: { bar: number }
}
type Types = {
TypeA: TypeA
TypeB: TypeB
}
type TypesName = keyof Types
/**
* Handles TypeA or TypeB objects, returning the appropriate type based on the input.
*/
function transform<N extends TypesName>(typeName: N, typeValue: Types[N]['input']): Types[N]['output'] {
switch (typeName) {
case 'TypeA':
return transformTypeA(typeValue) // Error message about assigning types may appear here
case 'TypeB':
return transformTypeB(typeValue) // Error message about assigning types may appear here
}
throw new Error('Unknown type')
}
function transformTypeA(typeA: TypeA['input']): TypeA['output'] {
return { foo: parseInt(typeA.foo) }
}
function transformTypeB(typeB: TypeB['input']): TypeB['output'] {
return { bar: parseInt(typeB.bar) }
}
const transformedValue = transform('TypeA', { foo: 'lol' })
console.log(transformedValue) // The transformedValue is now a type of { foo: number }