Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular - Type 'string' is not assignable to type 'boolean'

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?

like image 703
Mark Estrada Avatar asked Jul 21 '17 21:07

Mark Estrada


People also ask

Is not assignable to type boolean TypeScript?

The "Type 'X' is not assignable to type 'boolean'" TypeScript error occurs when a value that is not a boolean is assigned to something that expects a boolean . To solve the error, convert the value to a boolean or use a type guard to verify the value is a boolean before the assignment.

Is not assignable to type string?

The "Type 'string' is not assignable to type" TypeScript error occurs when we try to assign a value of type string to something that expects a different type, e.g. a more specific string literal type or an enum. To solve the error use a const or a type assertion.

Is not assignable to type Boolean or undefined?

The "Type 'boolean | undefined' is not assignable to type boolean" error occurs when a possibly undefined value is assigned to something that expects a boolean . To solve the error, use the non-null assertion operator or a type guard to verify the value is a boolean before the assignment.

Can a Boolean be undefined TypeScript?

You can assign true , false and undefined and null to boolean in TypeScript without strict null checks.


1 Answers

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)

like image 149
0mpurdy Avatar answered Oct 15 '22 00:10

0mpurdy