I have two types defined like this:
type Type1 = 'A' | 'B' | 'C';
type Type2 = 'D' | 'B' | 'F';
I have create 2 objects using these types like so:
const TYPE1 : { [ id in Type1 ] : {
label : string;
image : string;
} } = {
A: {
label: 'a',
image: 'a.jpg',
},
B: {
label: 'b',
image: 'b.png',
},
C: {
label: 'c',
image: 'c.gif',
},
};
const TYPE2 : { [ id in Type2 ] : {
label : string;
image : string;
val : number;
} } = {
D: {
label: 'd',
image: 'd.jpg',
val: 0,
},
B: {
label: 'b',
image: 'b.png',
val: 1,
},
F: {
label: 'f',
image: 'f.gif',
val: 2,
},
};
Since these 2 objects are very similar I want to create a generic function that can operate on both, so I was hoping to do this:
function doStuff<T>( typeIn : {[key in T] : { label : string; image : string } } ) {
// use T here for stuff
}
This doesn't work as I'm getting the following error:
Type 'T' is not assignable to type 'string | number | symbol'. Type 'T' is not assignable to type 'symbol'.(2322)
I can make the function work if I change the function signature to:
function doStuff( typeIn : {[key : string] : { label : string; image : string } } ) {
//oh oh, I no longer know if typeIn is using Type1 or Type2
}
Is there a way I can declare typeIn using the generic T?