Typescript: how to merge the representation (in tooltip) of this intersection?

后端 未结 1 610
梦毁少年i
梦毁少年i 2021-01-14 18:02

I have a function with an overload:

interface FunctionWithOverload {
    (): {
        a: 1
        b: 1
    }

    (arg: T): {
        a: 1
                


        
相关标签:
1条回答
  • 2021-01-14 18:08

    I've managed (with the help of TitianCernicova-Dragomir) to solve this! Like this:

    interface FunctionWithOverload {
        (): {
            a: 1
            b: 1
        }
    
        <T>(arg: T): Id<{
            a: 1
            b: 1
        } & (T extends number ? { c: 1 } : {})>
    }
    
    type Id<T>={} & { [P in keyof T] :T[P]}
    
    const fwo: FunctionWithOverload = () => {return {} as any}
    
    const result = fwo() // result has a nice type: {a: 1, b: 1}
    const result1 = fwo(1) // result1 DOES HAVE TOO!!! {a: 1, b: 1, c: 1} 
    

    Playground

    I think the way it works probably is: the TS engine considers mapped types as worthy of being named types, like interfaces, while any unions, intersections (like in the solution above) or basic types like string literals are not.

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