TypeScript typeof Function return value

前端 未结 3 2028
青春惊慌失措
青春惊慌失措 2020-12-29 18:16

Admit I have a function like this

const createPerson = () => ({ firstName: \'John\', lastName: \'Doe\' })

How can I, without dec

3条回答
  •  [愿得一人]
    2020-12-29 18:56

    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
    

提交回复
热议问题