Typescript type T or function () => T usage

后端 未结 1 1894
名媛妹妹
名媛妹妹 2021-01-15 13:50

You can see a demo in this playground.

I\'ve made a simple generic type which can represent either a variable or a function that returns a variable. But, unfortunate

相关标签:
1条回答
  • 2021-01-15 14:07

    You can write:

    type Initializer<T> = T extends any ? (T | (() => T)) : never
    
    function correct<T>(arg: Initializer<T>): T {
        return typeof arg === 'function' ? arg() : arg // works
        // arg is Initializer<T> & Function in the true branch
    }
    
    const r1 = correct(2) // const r1: 2
    const r2 = correct(() => 2) // const r2: number
    

    In the original version, arg is resolved to (() => T) | (T & Function) in the true branch. TS apparently can't recognize for this union function type, that both constituents are callable. At least in above version, it is clear for the compiler that you can invoke arg after a function check.

    Might also be worth to create a github issue for this case in the TypeScript repository - in my opinion T & Function should represent some (wide) type of function.

    0 讨论(0)
提交回复
热议问题