繁体   English   中英

即使属性未标记为只读,打字稿“无法分配给属性,因为它是常量或只读”

[英]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编译器将返回以下错误:

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

当显然没有用这种方式标记只读属性时,它是如何deafualts的。

你延长React.Component并将其定义propsReadonly<SetupProps>

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

资源

如果要分配一些默认值,可以使用类似以下内容的方法:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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