Skip to content

Assignment across the same type fails in TS 3.5 #31665

@domoritz

Description

@domoritz

I found an issue with assigning from one object to another when the types and key are the same. This issue did not occur in TS 3.4.

I understand that this is fixing unsound assignments but I wonder what the right pattern is now.

TypeScript Version: 3.5

Search Terms: keyof, unsound, assigment

Code

type D = {
    foo?: number,
    bar?: string,
};

const a: D = {};
const b: D = {};

const k = "foo" as keyof D;

a[k] = b[k];

Expected behavior:

No error

Actual behavior:

Type 'string | number | undefined' is not assignable to type 'undefined'.
  Type 'string' is not assignable to type 'undefined'.

I have to write this to fix the issue (is there a better way?)

type D = {
    foo?: number,
    bar?: string,
};

const a: D = {};
const b: D = {};

const k = "foo" as keyof D;

a[k] = b[k] as any;

Playground Link:

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions