Closed as not planned
Description
π 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
π» 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