13

Angular 4.3.1
Angular CLI 1.2.3
Typescript 2.3.4

Component Typescript file:

public saveName: string;
public overwrite: boolean;

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?

1 Answer 1

16

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

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

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.