[英]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: 纯JS方法产生正确的结果:
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 !!
可以使用
Boolean
内置或!!
执行类型转换 shortcut; 捷径; both
'false'
and 'true'
strings are truthy: 'false'
和'true'
字符串都是真实的:
true === Boolean('true');
true === !!'false';
Since booleans can be either true
or false
, it doesn't make sense to parse string value. 由于布尔值可以是
true
或false
,因此解析字符串值没有意义。 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. 考虑到
'true'
将转换为true
而'false'
将转换为false
,则不清楚将'foo'
字符串转换为什么 - 对于布尔值没有NaN
对应物,因为它们是布尔值。
The particular problem is specific to Angular component input, as another answer mentions. 另一个答案提到,特定问题是Angular组件输入特有的。
input="true"
is equal to input="{{ true }}"
, which is attribute binding , and input value will be a string. input="true"
等于input="{{ true }}"
,这是属性绑定 ,输入值将是一个字符串。
While [input]="true"
is property binding , and input value will be of the same type that was passed to the input. 虽然
[input]="true"
是属性绑定 ,但输入值与传递给输入的类型相同。 Boolean value will remain boolean and won't be needed to be converted. 布尔值将保持布尔值,不需要转换。
组件中的@input
应该用[]
表示,这应该可以解决您的问题
<component [input]="true"></component>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.