I'm trying to write a function that initialize Record<X,Y>
in typescript
my issue is that I'm having the error
X only refers to a type but is use as a value here.
In my case X will always be an enum
but I don't know how to precise it in the signature also
Here is the function I have written :
function initiateRecord<X extends string | number,Y>(enumX: typeof X, defaultValue: Y): Record<X,Y>{
const toReturn = {} as Record<X,Y>;
Object.keys(enumX).forEach(key => {
toReturn[key] = defaultValue;
});
return toReturn;
}
Complete code to test :
enum EnumA {
A = 'A',
B = 'B',
C = 'C',
}
function initiateRecord<X extends string | number,Y>(enumX: typeof X, defaultValue: Y): Record<X,Y>{
const toReturn = {} as Record<X,Y>;
Object.keys(enumX).forEach(key => {
toReturn[key] = defaultValue;
});
return toReturn;
}
class AA {
bb: Record<EnumA, boolean> = initiateRecord(EnumA, false);
constructor(){
}
}
const test = new AA();
test.bb[EnumA.A] = true;
alert(JSON.stringify(test));
Note that when I click on run it seems to work, but that error is bugging me, and i can't add it to my projct like that.