Skip to content

Mapped types cannot be reassigned to union type #55616

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
gutentag2012 opened this issue Sep 3, 2023 · 2 comments
Closed

Mapped types cannot be reassigned to union type #55616

gutentag2012 opened this issue Sep 3, 2023 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@gutentag2012
Copy link

gutentag2012 commented Sep 3, 2023

πŸ”Ž Search Terms

mapped types, union, union types, extract, narrow

πŸ•— Version & Regression Information

This is the behavior in every version I tried, and I reviewed the FAQ for entries about mapped type

⏯ Playground Link

https://www.typescriptlang.org/play?ts=5.3.0-dev.20230903#code/JYOwLgpgTgZghgYwgAgPICMBWBGZBvAKGWQGsIBPALmQHJsaBuI5EOAWwmoGcwpQBzJgF8CoSLEQoMmAEz5mZKrRmNm7APYBXcNRCa26aMIJhyABylYICMF2QBeNFlwAfJ7KYnzlzNbABZODMAFW8HeWIAbQBpClCLZFB3Py5ImkUaAF1MgH5qAFEAD15EMAAeaRSAGnxSCmpY8niUIQA+YU8EdRAeZHUrG0CzakrBoObwwmJsainiOqU6GirmYlYOahp1iGXmIRWhJhhtG2Bu5DgAE0vRsGD1IYqsZAhiiBBLu1uuVoAKfswIywAEoIn0BgEgpEAQA6RSZcIA4RAA

πŸ’» Code

interface Obj1 {
  key: '1';
  name: string;
}
interface Obj2 {
  key: '2';
  amount: number;
}
type Objects = Obj1 | Obj2;

type ObjectMapType = {
  [KeyType in Objects['key']]?: Extract<Objects, { key: KeyType }>;
};

const objectMap: ObjectMapType = {
  1: {
    key: '1',
    name: 'name',
  },
};
function addObjectToMap<Obj extends Objects>(obj: Obj) {
  objectMap[obj.key] = obj;
}

πŸ™ Actual behavior

The object map does not accept a new entry unless it is specifically typed as Obj1 or Obj2, therefore more broadly typed Objects are not accepted.

πŸ™‚ Expected behavior

Since the ObjectMapType uses a mapped type for Objects, all of its variations are included, so everything that is typed as Objects should be accepted.

Additional information about the issue

No response

@andrewbranch
Copy link
Member

Duplicate of #31445 (the repro there looks a little different, but the explanation works perfectly, and many of the other issues linked to that one look more similar to this)

@andrewbranch andrewbranch added the Duplicate An existing issue was already created label Sep 5, 2023
@typescript-bot
Copy link
Collaborator

This issue has been marked as "Duplicate" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Sep 8, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

3 participants