I've come across various questions similar to the one about Typescript return type depending on parameter
However, my issue is slightly different: the parameter type is not a basic JS/TS type, but rather a class type. In this case of class types, the solution provided in the aforementioned question does not seem to work.
class Foo {}
class Bar {}
// My attempts
// 1.
function update<T extends Foo | Bar>(item: T): T extends Foo ? 'Foo' : 'Bar' {
return {} as any
}
// 2.
function update(item: Foo): 'Foo'
function update(item: Bar): 'Bar'
function update(item: Foo | Bar): 'Foo' | 'Bar' {
return {} as any
}
// Testing
const foo = new Foo()
const bar = new Bar()
const result1 = update(foo) // typeof result1: "Foo"
const result2 = update(bar) // typeof result2: "Foo", expected "Bar" however
The code above highlights my attempt to determine the return type of the function update()
based on the parameter type, which can either be of type class Foo
or class Bar
. However, I have been unable to achieve the desired outcome. Any assistance would be greatly appreciated.