Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference should take advice from interfaces #19454

Closed
na-sa-do opened this issue Oct 24, 2017 · 1 comment
Closed

Type inference should take advice from interfaces #19454

na-sa-do opened this issue Oct 24, 2017 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@na-sa-do
Copy link

na-sa-do commented Oct 24, 2017

Bug? Suggestion? Oh well.

TypeScript Version: 2.7.0-dev.20171024

Code

interface OneOrTwo {
    ex: 1 | 2;
}

class Example implements OneOrTwo {
    ex = 1;
}

Expected behavior: The type of Example#ex is inferred to 1 | 2 and the example compiles.

Actual behavior: The type of Example#ex is inferred to number, which is not a subtype of 1 | 2, so the example does not compile.

Suggested solution?: If a property of a class has its type inferred from a default value, and that type isn't compatible with all interfaces the class explicitly implements, try inferring the intersection of the types required by the interfaces. So:

interface OneOrTwo {
    ex: 1 | 2;
}

interface TwoOrThree {
    ex: 2 | 3;
}

class Example implements OneOrTwo, TwoOrThree {
    ex = 2; // should be inferred as type (1 | 2) & (2 | 3), i.e. 2
}

For simplicity, if that type doesn't work, the original type (number here) should be used in error messages. Maybe the message should be changed, even.

@RyanCavanaugh
Copy link
Member

See #10570

@mhegazy mhegazy added the Duplicate An existing issue was already created label Oct 24, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 14, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants