Consider this sample JS function that requires type annotations:
const remap = (obj) => {
const mapped = {};
Object.keys(obj).forEach((key) => {
mapped[key] = !!key;
});
return mapped;
};
I am attempting to add types using generics (in this TS playground), but I keep encountering the following error:
Type 'Mapped<T>' is generic and can only be indexed for reading.(2862)
type Mapped<T> = {
[K in keyof T]?: boolean;
};
const remap = <T extends Record<string, unknown>>(
obj: T
) => {
const mapped: Mapped<T> = {};
Object.keys(obj).forEach((key) => {
mapped[key] = !!key; // Type 'Mapped<T>' is generic and can only be indexed for reading.(2862)
});
return mapped;
};
I am curious as to why TypeScript does not allow me to write to an object of a generic type, and if there might be another workaround. I expect TypeScript to recognize the type of mapped
and grant me permission to write to it, but it seems to restrict that.
Would utilizing as
during the return statement be my sole option?
const remapWithAs = <T extends Record<string, unknown>>(
obj: T
) => {
const mapped: Record<string, boolean> = {};
Object.keys(obj).forEach((key) => {
mapped[key] = !!key;
});
return mapped as Mapped<T>; // Is this my only choice?
};