简体   繁体   中英

Typescript / Angular : equivalent of plus operator for boolean type

In typescript we can converter a string to a number using :

let asText: string = "123";
let asNumerals: number = +asText;

How can the same be achieved for boolean types :

let asText: string = "true";
console.log(+asText); // NaN
console.log(typeof asText); // string
let b: boolean = +asText; // does not compile

A pure JS approach yields correct results:

let b: boolean = asText == "true"; // Works as expected but not good enough

But this solution is not good enough, example :

<component input="true"></component>

@Component()
export class Component {

    @Input()
    private input: boolean;


    ngOnInit() {
        console.log(typeof input); // string
    }

}

+ operator performs type conversion for numbers. As for booleans, falsy and truthy terms are used to describe coerced value. Type conversion can be performed with Boolean built-in or !! shortcut; both 'false' and 'true' strings are truthy:

true === Boolean('true');
true === !!'false';

Since booleans can be either true or false , it doesn't make sense to parse string value. Considering that 'true' would be converted to true and 'false' would be converted to false , it's unclear what would 'foo' string be converted to - there's no NaN counterpart for booleans, because they are booleans.

The particular problem is specific to Angular component input, as another answer mentions.

input="true" is equal to input="{{ true }}" , which is attribute binding , and input value will be a string.

While [input]="true" is property binding , and input value will be of the same type that was passed to the input. Boolean value will remain boolean and won't be needed to be converted.

组件中的@input应该用[]表示,这应该可以解决您的问题

<component [input]="true"></component>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM