TypeScript typeof Function return value

前端 未结 3 2013
青春惊慌失措
青春惊慌失措 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 = <T>(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<T> that obtains the return type of a function type.

    const hello = () => 'World'
    
    type Hello = ReturnType<typeof hello> // string
    
    0 讨论(0)
  • 2020-12-29 19:03

    Original Post

    TypeScript < 2.8

    I created a little library that permits a workaround, until a fully declarative way is added to TypeScript:

    https://npmjs.com/package/returnof

    Also created an issue on Github, asking for Generic Types Inference, that would permit a fully declarative way to do this:

    https://github.com/Microsoft/TypeScript/issues/14400


    Update February 2018

    TypeScript 2.8

    TypeScript 2.8 introduced a new static type ReturnType which permits to achieve that:

    https://github.com/Microsoft/TypeScript/pull/21496

    You can now easily get the return type of a function in a fully declarative way:

    const createPerson = () => ({
      firstName: 'John',
      lastName: 'Doe'
    })
    
    type Person = ReturnType<typeof createPerson>
    
    0 讨论(0)
  • 2020-12-29 19:05

    This https://github.com/Microsoft/TypeScript/issues/4233#issuecomment-139978012 might help:

    let r = true ? undefined : someFunction();
    type ReturnType = typeof r;
    
    0 讨论(0)
提交回复
热议问题