角度-不能将类型“字符串"分配给类型“布尔值"
角度4.3.1
Angular CLI 1.2.3
打字稿2.3.4
Angular 4.3.1
Angular CLI 1.2.3
Typescript 2.3.4
组件打字稿文件:
public saveName: string;
public overwrite: boolean;
以下标记失败,并显示当我运行ng build --prod
The following markup fails with Type 'string' is not assignable to type 'boolean' when I run ng build --prod
<span>{{!overwrite || saveName}}</span>
OR
<button *ngIf="!overwrite && saveName">Save</button>
但是,它可以在以下情况下正常工作:
However, it works fine with the following:
<span>{{saveName || !overwrite}}</span>
<span>{{overwrite || saveName}}</span>
<button *ngIf="saveName && !overwrite">Save</button>
<button *ngIf="overwrite && saveName">Save</button>
为什么会出现该错误?
更具体地说,为什么只有在字符串前面有取反的布尔值时才会显示该错误?
Why am I getting that error?
More specifically, why does that error only show up when I have a negated boolean come before a string?
尝试*ngIf="!overwrite && !!saveName"
将saveName
转换为布尔值
TypeScript给出该错误的原因大致是:您在应该使用布尔值的地方使用了字符串.
The reason TypeScript gives for the error is roughly: you are using a string where you should be using a boolean.
我认为它仅在这种情况下发生的原因是,如果您拥有true || anything
,则仅会评估第一个(因为如果第一个为true,则整个表达式将为true,而与其余情况无关)
The reason I think that it only happens in that circumstance is because if you have true || anything
only the first will be evaluated (because if the first is true the whole expression will true regardless of the rest)