I'm trying to create an object that is a relationships between between several item keys, and item key has different versions that have their own data types.
const myMap : MyMapObject = {
"foo": {
"1": {
type: "foo",
version: "1",
data: {
name: "bob"
}
},
"2" : {
type: "foo",
version: "2",
data: {
firstName: "Bob",
lastName: "Jones"
}
}
},
"bar" : {
"1": {
type: "bar",
version: "1",
data: {
age: 1
}
}
}
}
Here's my TypeScript:
type ItemTypes = "foo" | "bar";
type Version = string;
type Foo = {
"1": {
name: string;
};
"2": {
firstName: string;
lastName: string;
}
}
type Bar = {
"1": {
age: number;
}
}
type BaseTypeMap = {
"foo": Foo;
"bar": Bar;
}
type VersionMap<T extends ItemTypes> = BaseTypeMap[T];
type ItemObject<T extends ItemTypes, U extends keyof VersionMap<T>> = {
type: T;
version: U;
data: VersionMap<T>[U];
}
type MyMapObject = {
[K in ItemTypes] : {
[J in keyof VersionMap<K>] : ItemObject<K, J>;
}
}
function getDataForTypeAndVersion<T extends ItemTypes, U extends keyof VersionMap<T>> (itemKey: T, version: U) : ItemObject<T,U> {
const versionMap = myMap[itemKey] ;
const item = versionMap[version]; //Type 'U' cannot be used to index type 'MyMapObject[T]'.(2536) <-- Error here
return item;
}
//The function appears to work fine.
const foo1 = getDataForTypeAndVersion("foo", "1");
foo1.data.name;
foo1.data.firstName; //expected error
const foo2 = getDataForTypeAndVersion("foo", "2");
const foo3 = getDataForTypeAndVersion("foo", "3"); //expected error
const bar1 = getDataForTypeAndVersion("bar", "1");
const char1 = getDataForTypeAndVersion("chaz", "1"); //expected error
Just want to check - is this a dupe of this Stack Overflow question and this open bug?
(These appear to relate to array/tuple types, whereas mine are objects/maps).
If so, what is the recommended solution in my case?
If not, what is the cause of the error here?