Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot change value of key in an object with TypeScript

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
*/

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading