microsoft / microsoft/TypeScript

Nominal/branded key for `Record` disables checking/inferring of value type

Open
#43,852 6 comments 6 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

🔎 Search Terms

nominal, Record, branded

🕗 Version & Regression Information

3.3.3 through 4.3.2

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about nominal types and record types
⏯ Playground Link

Playground link with relevant code

💻 Code
type Id = string & { __id: 'id' }

type User = {
  id: Id;
  name: string;
}

type Users = Record<Id, User>;

type Users2 = Map<Id, User>;

type Users3 = Record<string, User>;

// This will not produce an error
// @ts-expect-error No name should be an error!
const users: Users = { id0: { id: 'id', } }

// type: [string, unknown][]
const entries = Object.entries(users);

const users2: Users2 = new Map();
// @ts-expect-error No name produces an error
users2.set('id' as Id, { id: 'id' as Id, })

// @ts-expect-error No name produces an error
const users3: Users3 = { id0: { id: 'id' as Id, } }

// type: [string, User][]
const entries3 = Object.entries(users3);
🙁 Actual behavior

Using a nominal/branded type as the key to a record type causes type checking of the value to be skipped. Additionally, inference will also fail and fallback to unknown, such as using Object.entries. Using a Map works as expected, but not a Record. I realize that the runtime behavior between a Map (real) and Record (type) is completely different, I'm just providing it as an example.

🙂 Expected behavior

I'd expect types to be preserved and checked, even when using a nominal/branded type as a key to a record.

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 running the linked TypeScript Playground repro with the Record<Id, User> and Object.entries examples, then compare them with the working Map and string-keyed Record cases. Trace the compiler's handling of branded keys and record values; done means value checking reports the missing name and Object.entries(users) preserves User instead of inferring unknown.

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
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.