![](/img/trans.png)
[英]Angular 2 | cannot assign to array because it is a constant or a read-only property
[英]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
并将其定义props
为Readonly<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.