admin管理员组

文章数量:1391960

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 piler 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.

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 piler 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.

Share Improve this question asked Nov 30, 2017 at 12:47 HentovHentov 4931 gold badge4 silver badges13 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

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

本文标签: