I am currently in the process of attempting to invoke a generic function by passing a dynamically-selected handler. The handler's parameter contains a `type` field that corresponds to a type string provided by the user. I am facing uncertainty on how to represent this scenario in TypeScript. What adjustments can I make to my types so that `problemFunction` accurately determines the generic type when calling `getAndUseFoo`?
interface Foo {
type: string;
}
interface FooA {
type: 'A';
}
interface FooB {
type: 'B';
}
const handlers = {
A: (fooA: FooA) => console.log(fooA),
B: (fooB: FooB) => console.log(fooB),
}
// An untyped library function that we know returns a type extending Foo
function fooFactory(type: string): any {
return type === 'A' ? {type: 'A'} : {type: 'B'};
}
// Retrieves a Foo instance and invokes a handler on it before performing additional tasks
function getAndUseFoo<T extends Foo>(type: string, handler: (foo: T) => any) {
const foo: T = fooFactory(type);
handler(foo);
// Carry out more operations using foo
}
function problemFunction(type: 'A' | 'B') {
// TypeScript is detecting handlers[type] as a union type with mismatched types
const foo = getAndUseFoo(type, handlers[type]);
}