microsoft / microsoft/TypeScript

Some types are incorrectly assignable from a generic distributive conditional type

Open
#32,066 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: Conditional Types
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

TypeScript Version: 3.5.1

Search Terms: generic conditional distributive assignable from

Code

type Keys<T extends object> = T extends unknown ? keyof T : never;

function f<T extends object>(keys: keyof T, moreKeys: Keys<T>) {
    keys = moreKeys;
}

// With this instantiation, `keys` is typed 'a',
// and `moreKeys` is typed 'a' | 'b' | 'c'. The latter
// should not be assignable to the former, but it happens
// in the generic context of the function `f`.
f<{ a: any, b: any } | { a: any, c: any }>('a', 'b');

Expected behavior:

Keys<T> should not be assignable to keyof T since Keys<T> is distributive and will produce a different type than keyof T when T is a union type.

Note that the reverse of this assignment, moreKeys = keys, errors for this exact reason; without a concrete T, it’s hard to tell what the relationship should be, so we simply have no relationship in place.

Actual behavior:

The unsafe assignment is allowed.

Playground Link

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 by reproducing the generic distributive conditional-type example in the linked Playground. Trace the type-checking path for assignability in the generic context, then add a regression test covering the unsafe assignment and the stated reverse-assignment behavior. Done means the call with 'b' is rejected because Keys is not assignable to keyof T.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.