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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47573890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:05:07  来源:igfitidea点击:

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

javascriptreactjstypescriptreadonly

提问by Hentov

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 compiler returns the following error:

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

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

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

How is deafualtsa readonly property, when its clearly not marked this way.

deafualts只读属性如何,当它明确没有以这种方式标记时。

采纳答案by Aleksey L.

You're extending React.Componentand it defines propsas Readonly<SetupProps>

你正在扩展React.Component,它定义propsReadonly<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});
}