I am unable to change the value of a key in an object with typescript. These are the types
export enum FOO_TYPES {
red = "red",
green = "green"
}
export type FooTypes = {
[key in keyof typeof FOO_TYPES]: boolean
}
enum SOME_OTHER_ENUM {
a = "abc",
d = "def",
e = "ghi"
}
export interface SomeMoreData {
id: number,
key: SOME_OTHER_ENUM,
priceA: number,
priceB: number,
red: boolean,
green: boolean,
}
type ProjectProps = {
[key in SOME_OTHER_ENUM]?: {
project: SomeMoreData ,
amountPriceAPriceB: {
sumPriceA: number;
sumPriceB: number;
}
}
}
interface GroupedProjectProps {
[FOO_TYPES.red]: ProjectProps,
[FOO_TYPES.green]: ProjectProps
};
Now I am having this function
const someFunc = (projects: GroupedProjectProps) => {
const availableTypes: FooTypes = {
red: false,
green: false
};
(Object.keys(projects) as Array<keyof typeof FOO_TYPES >).map(type => {
if (Object.keys(projects[type]).length > 0) availableTypes[type] = true
})
}
Which gives me the following error
Cannot assign to ‘red’ because it is a read-only property.
Cannot assign to ‘green’ because it is a read-only property.
Which I do not understand why this error is coming up…
Here is a playground
(Object.keys(projects) as Array<keyof typeof FOO_TYPES >).map(type=> {
const a = projects[compensateType]
if (Object.keys(a).length > 0) availableTypes[type] = true
})
...
>Solution :
The problem lies in the fact that your FooTypes
has readonly properties.
export type FooTypes = {
[key in keyof typeof FOO_TYPES]: boolean
}
/**
type FooTypes = {
readonly red: boolean;
readonly green: boolean;
}
*/
See readonly modifier for properties
You can use Mapping Modifiers to make the properties mutable
export type FooTypes = {
-readonly [key in keyof typeof FOO_TYPES]: boolean
}
/**
type FooTypes = {
red: boolean;
green: boolean;
}
*/