-
Notifications
You must be signed in to change notification settings - Fork 12.5k
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
Erroneous error when assigning to string literal union type #11714
Comments
Yes, I just tried with |
I'm reopening this because I just found another very similar case which is still broken: interface I {
xOrY: 'x' | 'y'
}
class C implements I {
xOrY = 'x'
} This produces the error:
Adding this seemingly superfluous type ascription fixes it: class C implements I {
xOrY = 'x' as 'x' | 'y'
} |
@pelotom this error is correct. Because the field isn't interface I {
xOrY: 'x' | 'y'
}
class C implements I {
xOrY = 'x'; // note: xOrY of type 'string'
}
let c = new C();
c.xOrY = 'z';
fn(c);
function fn(i: I) {
if (i !== 'x' && i !== 'y') throw new Error('Inconceivable!');
} Side note, correct inference for |
But... What I'm saying is that the inferred type of the field |
interface I {
xOrY: 'x' | 'y'
}
const c: I = { xOrY: 'x' }
c.xOrY = 'z' // ERROR: Type '"z"' is not assignable to type '"x" | "y"'. |
Ok, thanks for the pointer! |
TypeScript Version: 2.0.3 / nightly (2.1.0-dev.201xxxxx)
Code
Expected behavior:
The code should type check.
Actual behavior:
The last line is flagged with an error:
It can be fixed by giving
xOrY
a type annotation to say that it has type"x" | "y"
, but the compiler seems to have already inferred that it has this type (based on whatatom-typescript
's show-types-on-hover feature is telling me), so that doesn't seem like it should be necessary.When the union is of non-string literal types, there is no such error.
The text was updated successfully, but these errors were encountered: