【问题标题】:Typescript "Cannot assign to property, because it is a constant or read-only" even though property is not marked readonly即使属性未标记为只读,打字稿“无法分配给属性,因为它是常量或只读”
【发布时间】:2017-11-30 12:47:01
【问题描述】:

我有以下代码

type SetupProps = {
    defaults: string;
}

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

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

无法分配给“默认值”,因为它是常量或只读的 属性。

deafualts 是一个只读属性,它显然没有以这种方式标记。

【问题讨论】:

    标签: javascript reactjs typescript readonly


    【解决方案1】:

    您正在扩展 React.Component 并将 props 定义为 Readonly&lt;SetupProps&gt;

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

    【讨论】:

    • 有道理。但是我如何才能修改(分配)我的 props 对象的任何值。
    • 添加了一个例子。希望有帮助
    猜你喜欢
    • 2018-12-07
    • 2018-10-14
    • 1970-01-01
    • 2019-01-09
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多