I am trying to create a function with return type depending on whether optional parameter (factory) was passed or not
I tried to do it like this:
type Factory<T> = (data: any) => T;
function getObject<T>(id: number, factory?: Factory<T>): Factory<T> extends undefined ? any : ReturnType<Factory<T>> {
let obj; // some entity from db in real app
return factory ? factory(obj) : obj;
}
getObject(1, () => new Date()).getDate(); // OK, treated as date
getObject(1, () => new String()).toLocaleLowerCase(); // OK, treated as string
getObject(1).anything; // ERROR, typescript treat it as {} instead of any
but It doesn't work as expected when I don't pass factory
parameter. How can I fix it?
https://stackblitz.com/edit/typescript-xci2gs
答案 0 :(得分:1)
设法通过将签名更改为
来修复它function getObject<T extends Factory<any>>(id: number, factory?: T): T extends undefined ? any : ReturnType<T> {