Typescript "Cannot assign to property, because it is a constant or read-only" 即使 属性 未标记为只读

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

我有以下代码

type SetupProps = {
    defaults: string;
}

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

当尝试运行此代码时,TS 编译器returns出现以下错误:

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

为什么 deafualts 是只读的 属性,显然没有这样标记。

您正在扩展 React.Component 并将 props 定义为 Readonly<SetupProps>

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

Source

如果你想分配一些默认值,你可以使用类似的东西:

constructor({ defaults = 'Whatever' }: Partial<SetupProps>) {
    super({defaults});
}