I have an interesting and, I think, a little crazy question. The answer to which I not only couldn’t find, but I couldn’t even figure out how to briefly formulate it for a search query. And so, the question is:
How to declare a type in typescript for a function that can take either a function or something else as a single argument. And if it’s a function, it calls it and returns the result of the function, and if it’s not a function, then it just returns a value?
Simply put, it calls a function if it is a function.
My function without types:
export function funcfi(val: any): any {
return typeof val === "function" ? val() : val
}
My function with types:
export function funcfi<T>(val: ()=>T|T): T {
return typeof val === "function" ? val() : val
}
The LSP server reports that there are no errors, BUT when I call a function in the code to which I pass an element from Record<string, string|Function>, the LSP does not like it.
Screenshot with function call
And I understand that this is because the Record element can be a function that is passed to funcfi, and the declaration of the type funcfi turns into something similar:
funcfi(val: (()=>Function|string)|(Function|string )): (Function|string)
Which is wrong, because my result shouldn’t be a function anyway.
.
Of course, I can declare the types as any, and everything will work fine. But I really want to know how this can be specified using the TypeScript type system.
I also want to say that I am only interested in declaring types, and not in correctly writing functions or application logic — this is my personal pet-project, and I do what I want in it. Thank you in advance.
Ruslan D. Revellved is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.