Skip to content

Inference fails for return-type of intersection between class and generic type #5456

Closed
@fongandrew

Description

@fongandrew

When a generic type is used in an intersection type passed to a function, TS fails to infer that generic type.

Example:

interface Man {
    walks: boolean;
}

interface Bear {
    roars: boolean;
}

interface Pig {
    oinks: boolean;
}

declare function pigify<T>(y: T & Bear): T & Pig;
declare var mbp: Man & Bear;

pigify(mbp).oinks; // OK, mbp is treated as Pig
pigify(mbp).walks; // ERROR, mbp not recognized as Man

Playground: http://www.typescriptlang.org/Playground#src=interface%20Man%20%7B%0D%0A%09walks%3A%20boolean%3B%0D%0A%7D%0D%0A%0D%0Ainterface%20Bear%20%7B%0D%0A%09roars%3A%20boolean%3B%0D%0A%7D%0D%0A%0D%0Ainterface%20Pig%20%7B%0D%0A%09oinks%3A%20boolean%3B%0D%0A%7D%0D%0A%0D%0Adeclare%20function%20pigify%3CT%3E(y%3A%20T%20%26%20Bear)%3A%20T%20%26%20Pig%3B%0D%0Adeclare%20var%20mbp%3A%20Man%20%26%20Bear%3B%0D%0A%0D%0Apigify(mbp).oinks%3B%20%2F%2F%20OK%2C%20mbp%20is%20treated%20as%20Pig%0D%0Apigify(mbp).walks%3B%20%2F%2F%20Not%20OK%2C%20mbp%20not%20recognized%20as%20Man%0D%0A

This seems like the inverse of #2211. Unlike union types however, the use of an intersection type in the param should provide enough information to make the required inference.

That is, if I pass a value of type Man & Bear to a function expecting T & Bear, then T should either be Man or Man & Bear, either of which would be enough to infer that T has all of the properties expected of Man. Instead, TS seems to be inferring T to be of type {}.

Am I missing something here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    CommittedThe team has roadmapped this issueFixedA PR has been merged for this issueSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions