在 typescript 中,我们可以使用以下方法将字符串转换为数字:
let asText: string = "123";
let asNumerals: number = +asText;
如何对 bool 类型实现同样的效果:
let asText: string = "true";
console.log(+asText); // NaN
console.log(typeof asText); // string
let b: boolean = +asText; // does not compile
纯 JS 方法产生正确的结果:
let b: boolean = asText == "true"; // Works as expected but not good enough
但是这个解决方案还不够好,例如:
<component input="true"></component>
@Component()
export class Component {
@Input()
private input: boolean;
ngOnInit() {
console.log(typeof input); // string
}
}
最佳答案
+
运算符对数字进行类型转换。至于 bool 值,falsy和 truthy术语用于描述强制值。可以使用内置的 Boolean
或 !!
快捷方式执行类型转换; 'false'
和 'true'
字符串都是真实的:
true === Boolean('true');
true === !!'false';
由于 bool 值可以是true
或false
,因此解析字符串值没有意义。考虑到 'true'
将被转换为 true
而 'false'
将被转换为 false
,目前还不清楚'foo'
字符串会被转换成什么 - bool 值没有对应的 NaN
,因为它们是 bool 值。
正如另一个答案提到的那样,特定问题特定于 Angular 组件输入。
input="true"
等于input="{{ true }}"
,即attribute binding , 输入值将是一个字符串。
虽然 [input]="true"
是 property binding ,并且输入值将与传递给输入的类型相同。 bool 值将保持 bool 值,不需要转换。
关于javascript - typescript /Angular : equivalent of plus operator for boolean type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48041694/