myFavoriteNumber = true; // index.ts(2,1): error TS2322: Type 'boolean' is not assignable to type 'string | number'. // Type 'boolean' is not assignable to type 'number'.

联合类型使用 | 分隔每个类型。

这里的 let myFavoriteNumber: string | number 的含义是,允许 myFavoriteNumber 的类型是 string 或者 number ,但是不能是其他类型。

这是JavaScript所欠缺的,对于变量类型的约束,对于长期维护大型的开发项目,TypeScript已经成为必然

但在实际运用中,我们可能需要使用null或者undefined去释放某个变量,对于JavaScript来说,直接赋值,让其覆盖前置内容即可,但是 TypeScript并不支持此操作 。于是有人就考虑使用声明联合类型来强行释放

可以看到,TypeScript并没有理解我们的操作,也就是说其已经不支持之前不严谨的覆盖,为了得到相应的释放空间的效果,我们需要使用一个特殊操作:

!的用法:

用在赋值的内容后,使null和undefined类型可以赋值给其他类型并通过编译

let morton:string
morton = null //报错
morton = undefined //报错
morton = null!
morton = undefined!

有关更多TypeScript的内容博主会继续更新,希望大家相互交流~

null undefined 都有各自的类型名称。这些类型本身没有用处,因为我们只能将 null undefined 赋值 给定义为 null undefined 类型的变量。 let u: undefined = undefined u = 'string' // compile error let n: null = null n = 43 //compile error 默认情况...
Strict object literal assignment checking (严格的对象 赋值 检查)对象 赋值 时必需严格按照声明时指定的属性类型以及属性个数.var x: { foo: number }; x = { foo: 3 } x = { foo: 1, baz: 2 }; // 错误, 初始化时没有指名有`baz`属性.var y: { foo: number, bar?: numb