Skip to content

TS 3.5 new error when using keyof with assignment to copy property #31382

Closed

Description

@mjbvz

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:

  • keyof
  • property

Code

export interface I {
    x: string;
    y: number;
}

function copy(from: I, to: I, key: keyof I) {
    const value = from[key];
    if (typeof value === 'string') {
        to[key] = value
    }
} 

Expected behavior:
This compiles under TS 3.4.5 without any errors

Actual behavior:
In TS 3.5, this is a compile error:

Type 'string' is not assignable to type 'string & number'.
  Type 'string' is not assignable to type 'number'.

This is a reasonable error IMO, the change should just be noted somewhere (an issue may already exist but I wasn't sure which keywords to search for). We saw this in the VS Code codebase

Playground Link:

https://www.typescriptlang.org/play/#src=export%20interface%20I%20%7B%0D%0A%20%20%20%20x%3A%20string%3B%0D%0A%20%20%20%20y%3A%20number%3B%0D%0A%7D%0D%0A%0D%0Afunction%20copy(from%3A%20I%2C%20to%3A%20I%2C%20key%3A%20keyof%20I)%20%7B%0D%0A%20%20%20%20const%20value%20%3D%20from%5Bkey%5D%3B%0D%0A%20%20%20%20if%20(typeof%20value%20%3D%3D%3D%20'string')%20%7B%0D%0A%20%20%20%20%20%20%20%20to%5Bkey%5D%20%3D%20value%0D%0A%20%20%20%20%7D%0D%0A%7D%20

Related Issues:

Activity

  1. jack-williams commented on May 14, 2019

    @jack-williams
    Collaborator

    The PR introducing the change was this one #30769

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Breaking ChangeWould introduce errors in existing code

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions