microsoft / microsoft/TypeScript

Cannot assign property to same type with generic key

Open
#32,693 11 comments 18 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Experience Enhancement Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.6.0-dev.20190803

Search Terms: assigning keyof generic key

Code

type A = { a: number }
type B = { b: number }

interface Foo {
    a: A
    b: B
}

declare let target: Foo
declare let source: Foo
declare let key: keyof Foo

target[key] = source[key]

Expected behavior:

I expect it to allow the assignment. Since typeof target and typeof source are the same, I expect typeof target[key] to always be the same as typeof source[key].

Actual behavior:

error TS2322: Type 'A | B' is not assignable to type 'A & B'.

Playground Link: https://www.typescriptlang.org/play/#code/C4TwDgpgBAglC8UDeUCGAuKA7ArgWwCMIAnKAXwChRIoAhBZKAzXQk8iigSy2BIDNUAY2gAxAPbjkFKLLSYYMuczoVKFACYQhAG1TFoOiMCjB9Ac2OYJ4zdr0GoRkwGdxOYiOuS7u-YeMoAGsIEEwQkHF+KBtOM2JLYABtCIBdBjcPERTQ1IogA

Related Issues: #31665 (but it was closed and the comments seem to indicate that this should work 🤔) ping @RyanCavanaugh

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal TypeScript example in the issue and reproduce the TS2322 diagnostic in the linked Playground. Read related issue #31665 and investigate the type-checking path for indexed assignment with a keyof generic key. Done means the shown assignment is accepted while preserving soundness for differing source and target types.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.