Skip to content

ReturnType of Intersection Types #25459

Closed

Description

TypeScript Version: 2.9.2 and 3.0.0-dev.20180705

Search Terms:
typescript intersection ReturnType

Code

const foo = () => ({
    foo: 'bar'
})

const bar = () => ({
    bar: 'baz'
})

type Test = typeof foo & typeof bar

type Test2 = ReturnType<Test>

Expected behavior:
I would expect Test2 to be a union of ReturnType of "foo" and "bar"

Actual behavior:
I only get the ReturnType of "bar"

Playground Link:
http://www.typescriptlang.org/play/#src=const%20foo%20%3D%20()%20%3D%3E%20(%7B%0D%0A%20%20%20%20foo%3A%20'bar'%0D%0A%7D)%0D%0A%0D%0Aconst%20bar%20%3D%20()%20%3D%3E%20(%7B%0D%0A%20%20%20%20bar%3A%20'baz'%0D%0A%7D)%0D%0A%0D%0Atype%20Test%20%3D%20typeof%20foo%20%26%20typeof%20bar%0D%0A%0D%0Atype%20Test2%20%3D%20ReturnType%3CTest%3E%0D%0A

You will have to excuse if I am being ignorant on this and it actually is expected behaviour :-)

Activity

  1. mhegazy commented on Jul 5, 2018

    @mhegazy
    Contributor

    ReturnType (and conditional types on signatures in general) only operate on single overload. For intersection, union or overloads, the first is always picked.

    #6606 tracks adding call types.

  2. christianalfoni commented on Jul 5, 2018

    @christianalfoni
    Author

    Mohamed Hegazy (@mhegazy) Aha, I see... thanks for the quick response!

  3. christianalfoni commented on Jul 6, 2018

    @christianalfoni
    Author

    Okay, so this black magic TypeScript code actually solves it:

    type UnionToIntersection<U> = 
      (U extends any ? (k: U)=>void : never) extends ((k: infer I)=>void) ? I : never
    
    const foo = () => ({
        foo: 'bar'
    })
    
    const bar = () => ({
        bar: 'baz'
    })
    
    type Test = typeof foo | typeof bar // Notice the OR here
    
    type Test2 = UnionToIntersection<ReturnType<Test>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions