Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript "Cannot assign to property, because it is a constant or read-only" even though property is not marked readonly

I have the following code

type SetupProps = {
    defaults: string;
}

export class Setup extends React.Component<SetupProps, SetupState> {
    constructor(props: any) {
        super(props);
        this.props.defaults = "Whatever";
}

When trying to run this code the TS compiler returns the following error:

Cannot assign to 'defaults' because it is a constant or a read-only property.

How is deafualts a readonly property, when its clearly not marked this way.

like image 865
Hentov Avatar asked Nov 30 '17 12:11

Hentov


1 Answers

You're extending React.Component and it defines props as Readonly<SetupProps>

class Component<P, S> {
    constructor(props: P, context?: any);
    ...
    props: Readonly<{ children?: ReactNode }> & Readonly<P>;
    state: Readonly<S>;
    ...
}

Source

If you want to assign some default values, you can go with something like:

constructor({ defaults = 'Whatever' }: Partial<SetupProps>) {
    super({defaults});
}
like image 148
Aleksey L. Avatar answered Nov 11 '22 03:11

Aleksey L.