Typescript"无法分配给属性,因为它是常量或只读",即使属性未标记为只读

Hen*_*tov 8 javascript readonly typescript reactjs

我有以下代码

type SetupProps = {
    defaults: string;
}

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

尝试运行此代码时,TS编译器返回以下错误:

无法分配为"默认值",因为它是常量或只读属性.

如何是deafualts一个只读属性,当它显然没有标记这个样子.

Ale*_* L. 1

你正在扩展React.Component它定义propsReadonly<SetupProps>

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

来源

如果您想分配一些默认值,您可以使用以下内容:

constructor({ defaults = 'Whatever' }: Partial<SetupProps>) {
    super({defaults});
}
Run Code Online (Sandbox Code Playgroud)

  • 说得通。但是我如何才能修改(分配)我的 props 对象的任何值。 (4认同)