Typescript 使用| |运算符将布尔值赋给数字-奇怪的行为

Typescript 使用| |运算符将布尔值赋给数字-奇怪的行为,typescript,types,typescript-typings,typing,Typescript,Types,Typescript Typings,Typing,根据typescript类型系统,无法分配给 但是,我有一些Javascript的背景知识,我已经尝试了下一批代码,结果对我来说相当不清楚: let booleanVariable: boolean = false; let numberVariable: number = booleanVariable || 1; // compiles just fine > numberVariable = 1 如果要将“| | 1”更改为“| | 0”,则会出现编译器错误: let boolea

根据typescript类型系统,无法分配给

但是,我有一些Javascript的背景知识,我已经尝试了下一批代码,结果对我来说相当不清楚:

let booleanVariable: boolean = false;
let numberVariable: number = booleanVariable || 1;
// compiles just fine > numberVariable = 1
如果要将“| | 1”更改为“| | 0”,则会出现编译器错误:

let booleanVariable: boolean = false;
let numberVariable: number = 0 || booleanVariable;
// type false is not assignable to number
如果要将“booleanVariable”更改为“true”,则会出现编译器错误:

let booleanVariable: boolean = true;
let numberVariable: number = booleanVariable|| 1;
// type true is not assignable to type number

如果将true更改为false并用“| |”运算符替换操作数顺序,则可能会有更多的调整。如果有人能根据上述例子解释这种行为,我将不胜感激

在下一行中,
booleanVariable
的类型不是
boolean
,而是
false

let booleanVariable: boolean = false;
通过将变量悬停在游乐场或IDE中,似乎看不到真正的类型。但如果你需要被说服,你可以:

const booleanVariable: boolean = false ;
const tmp = booleanVariable; // Here the type of `tmp` is inferred as `false`
下面是如何将
布尔变量
声明为实
布尔变量

let booleanVariable = false as boolean;
现在,下一条指令是一个错误:

let numberVariable: number = booleanVariable || 1; // Error: Type 'true | 1' is not assignable to type 'number'.
在JavaScript
0
is中,表达式
0 | | booleanVariable
总是返回
booleanVariable
。因此,TypeScript推断表达式的类型是
布尔变量的类型

let numberVariable: number = 0 || booleanVariable; // Error: Type 'boolean' is not assignable to type 'number'.

谢谢你的解释。我认为'false | true'只是'boolean'类型的代表,因此,如果我要将某个值为'false | true'的对象声明为'boolean',则包含此声明的表达式的行为将与您使用'as boolean'显示的一样。