Skip to content

Issue implementing interface #14954

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

Closed
testerez opened this issue Mar 31, 2017 · 5 comments
Closed

Issue implementing interface #14954

testerez opened this issue Mar 31, 2017 · 5 comments
Labels
Duplicate An existing issue was already created

Comments

@testerez
Copy link

TypeScript Version: 2.2.2

Code

interface I {
  foo: 'foo' | 'bar';
}

interface IClass {
  i: I;
}

class C implements IClass {
  i = { foo: 'foo' };
}

Expected behavior:
no error

Actual behavior:

Class 'C' incorrectly implements interface 'IClass'.
Types of property 'i' are incompatible.
Type '{ foo: string; }' is not assignable to type 'I'.
Types of property 'foo' are incompatible.
Type 'string' is not assignable to type '"foo" | "bar"'.

@ghost
Copy link

ghost commented Mar 31, 2017

The type of 'foo' will be widened to string in this case. You can fix this by adding a type annotation: i: I = { foo: 'foo' };.

@vkurchatkin
Copy link
Contributor

Typescript is unable to infer literal types, unless it is a constant. For example:

let x = 1;
const y: 1 = x; // error, but shouldn't be
const x = 1;
const y: 1 = x; // no error
const x = { foo: 'bar' };
const y: { foo: 'bar' } = x; // error, but shouldn't be
const x: { foo: 'bar' } = { foo: 'bar' };
const y: { foo: 'bar' } = x; // no error

@testerez
Copy link
Author

@Andy-MS yes I did something similar: i = { foo: 'foo' } as I;
But It seams like typescript could do better here...

@vkurchatkin in your third example, x is constant but not x.foo...

@vkurchatkin
Copy link
Contributor

@testerez right, you can't make property a constant in TypeScript. Still, this shouldn't be an error.

@RyanCavanaugh
Copy link
Member

Duplicate #7011 - if the initializer were contextually typed this would work as expected

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Apr 3, 2017
@mhegazy mhegazy closed this as completed Apr 21, 2017
@microsoft microsoft locked and limited conversation to collaborators Jun 21, 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

4 participants