Angular - 类型“字符串"不可分配给类型“布尔值" [英] Angular - Type 'string' is not assignable to type 'boolean'

查看:36
本文介绍了Angular - 类型“字符串"不可分配给类型“布尔值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

角 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

<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 转换为一个布尔值

Try *ngIf="!overwrite && !!saveName" to cast saveName to a boolean

TypeScript 给出错误的原因大致是:您在应该使用布尔值的地方使用了字符串.

The reason TypeScript gives for the error is roughly: you are using a string where you should be using a boolean.

我认为它只发生在那种情况下的原因是因为如果你有 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)

这篇关于Angular - 类型“字符串"不可分配给类型“布尔值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆