简体   繁体   中英

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.

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});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM