Skip to content

Mapped types cannot be reassigned to union typeΒ #55616

Closed as not planned
Closed as not planned
@gutentag2012

Description

@gutentag2012

πŸ”Ž 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions