Admit I have a function like this
const createPerson = () => ({ firstName: \'John\', lastName: \'Doe\' })
How can I, without dec
Adapted from https://github.com/Microsoft/TypeScript/issues/14400#issuecomment-291261491
const fakeReturn = (fn: () => T) => ({} as T)
const hello = () => 'World'
const helloReturn = fakeReturn(hello) // {}
type Hello = typeof helloReturn // string
The example in the link uses null as T
instead of {} as T
, but that breaks with Type 'null' cannot be converted to type 'T'.
The best part is that the function given as parameter to fakeReturn
is not actually called.
Tested with TypeScript 2.5.3
TypeScript 2.8 introduced some predefined conditional types, including the ReturnType
that obtains the return type of a function type.
const hello = () => 'World'
type Hello = ReturnType // string