[英]Cannot assign to 'Boolean' because it is a constant or a read-only property
I am creating a typescript object to represent read/write permissions in my app, but I came across this quirk in assigning the variables that makes no sense to me. 我正在创建一个打字稿对象来表示我的应用程序中的读/写权限,但是在分配对我来说毫无意义的变量时遇到了这个怪癖。 Hopefully, someone can look at this and tell me what I am doing wrong.
希望有人可以看看这个,并告诉我我做错了什么。
export class Permission {
watcher:Object = { read:Boolean = true};
}
The previous code results in a error which says: 先前的代码会导致错误,提示:
[ts] Cannot assign to 'Boolean' because it is a constant or a read-only property. [ts]无法分配给'Boolean',因为它是常量或只读属性。 const Boolean: BooleanConstructor
const布尔值:BooleanConstructor
I'm probably just doing something stupid, so apologies in advance if this is super newbish. 我可能只是在做一些愚蠢的事情,所以如果这超级新奇,请提前道歉。
If you intended to type your watcher
property to be an object with property read
, then it should be typed something like this: 如果您打算将
watcher
属性键入为具有属性read
的对象,则应键入类似以下内容的对象:
export class Permission {
// The part after the ":" is the type definition of the property.
// The part after "=" is its value
watcher: {
read: boolean
} = { read: true };
}
What you currently have is probably a syntactic error. 您当前拥有的可能是语法错误。 You probably do not want to override the built-in constructor
Boolean
with Boolean = true
您可能不想使用
Boolean = true
覆盖内置的构造函数Boolean
You are trying to assign a JSON object with { read: true }
, declaring it as type Boolean is just redundant (because true
and false
are always Boolean) typescript infers the type, and it's an invalid JSON structure. 您正在尝试使用
{ read: true }
分配一个JSON对象,将其声明为Boolean类型只是多余的(因为true
和false
始终是Boolean)typescript会推断类型,并且它是无效的JSON结构。
JSON has this format: JSON具有以下格式:
{
key: value,
key2: value2
}
Notice there are no equal signs ( = ) in a JSON, only : to separate the keys and values. 请注意,JSON中没有等号( = ),只有:用来分隔键和值。
Now I see the class syntax is confusing you, because it does have an equal sign, but It's only for the assignment. 现在,我看到类语法使您感到困惑,因为它确实具有等号,但这仅用于赋值。 After the assignment you don't need to have an equals sign.
分配后,您不需要等号。
Your final class definition should look something like this: 您的最终课程定义应如下所示:
export class Permission {
watcher = { read: true };
}
You would need interfaces for more complex objects, in case you want optional variables or dependencies on other objects. 如果需要可选变量或对其他对象的依赖关系,则需要用于更复杂对象的接口。 For a small object typescript will understand the structure by the types.
对于小型对象,打字稿将通过类型来理解结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.