-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Incorrect type assignment error #17561
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
Comments
The error is correct. It would be unsound to assign |
Ok... I can see your argument. However this still fails:
|
@kitsonk I doubt that's what's going on. TypeScript allows unsound reassignments in many places; for example: const t2: typeTwo = {name: 'okay'}
const t1: typeOne = t2;
t1.name = undefined; // no error
console.log(typeof t2.name) // 'undefined' In the absence of in/out parameters or strict Additionally, discriminated unions specifically allow assignments like above, despite being unsound in the same mutation cases: interface A {
type: 'A';
}
interface B {
type: 'B';
}
function doMoreStuff(input: A | B) {
let b: B;
if (input.type == 'B') {
b = input; // no error
}
} My guess is that the control-flow analysis just isn't trying to narrow the type of the object containing a property if the type of the property is narrowed. In fact you can make the compiler narrow the parent object, with a user-defined type guard: function hasStringName(x: any): x is { name: string } {
return (typeof x.name === 'string');
}
function doStuff(input: typeOne) {
let objectWithName: typeTwo;
if (hasStringName(input)) {
objectWithName = input; // no error
}
} which would be my suggested workaround. |
@sandersn spread operator bug? Thoughts? |
@RyanCavanaugh The behaviour is the same whether or not you use the spread operator. I think @Roaders was trying to show that the error happens even if you try to get the compiler to consider the properties of I'm pretty sure this is just a feature that control flow doesn't have right now — it mostly just narrows, and there's nothing to narrow here because Note: You'll see that narrowing is occurring if you look at the type of |
@rbuckton and @weswigham suggested that
|
Doesn't seem all that impactful, plus it's technically not sound |
TypeScript Version: 2.4.0 / nightly (2.5.0-dev.201xxxxx)
Code
(playground)
Expected behavior:
should be able to assign
input
toobjectWithName
as we have already tested to see thatname
is defined.Actual behavior:
Get an error:
Type 'typeOne' is not assignable to type 'typeTwo'. Property 'name' is optional in type 'typeOne' but required in type 'typeTwo'.
The text was updated successfully, but these errors were encountered: