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 assignment between object types fails even when compatibility was checked through type-guards on properties #18304

Closed
fpascutti opened this issue Sep 7, 2017 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@fpascutti
Copy link

From section 3.11.4 (assignment compatibility) of the specification, an object type T should be assignable from an object type S when all T's properties exist on type S (same name) and each can be assigned from the corresponding property on type S.
However this does not work when property assignability was proven through a type-guard.

TypeScript Version: 2.5.2

Code

interface Widget {
  readonly data: string | number;
}
interface Gadget {
  readonly data: string;
}

function foo(g: Gadget): void {
  console.log(g.data);
}
function bar(w: Widget): void {
  if (typeof w.data === "string") {
    const d: string = w.data; // `w.data` correctly recognized as a `string`
    foo(w); // however `w` cannot be used as a `Gadget`
  }
}

Expected behavior:

Compiles successfully.

Actual behavior:

Compilation fails with:

error TS2345: Argument of type 'Widget' is not assignable to parameter of type 'Gadget'.
  Types of property 'data' are incompatible.
    Type 'string | number' is not assignable to type 'string'.
      Type 'number' is not assignable to type 'string'.
@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Sep 7, 2017
@RyanCavanaugh
Copy link
Member

See #10065

@fpascutti
Copy link
Author

Thanks. I did not find this issue.
Your latest comment makes sense by the way.

@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

2 participants