functionsum(a: number, b: number) { return a + b }
类型推断
数组的类型推断:
对象的类型推断:
any类型
1 2 3 4 5 6 7
let mo: any = 'morales.com.cn' mo = [] mo = {} mo = 123 mo = true mo = null mo = undefined
unknown 与 any 的区别:unknown 是未知类型,进行类型检测;any 是任何类型,不进行类型检测
将 string 等类型赋值给 any 不会报错,但赋值给 unknown 会报错
解决办法:使用 as 断言
1 2 3 4 5 6
let hh: unknown = 'as' let b: string = hh asstring
let str: string = '99' let c: number = str as unknown asnumber console.log(c)
void 与 never 类型
void 类型只能赋值为undefined,never为什么都没有
1 2 3 4 5 6
let m: void = undefined console.log(m)
functionth():never{ thrownewError('OhNo') }
函数
函数的声明
1 2
let mno = () =>'morales.com.cn' let func: Function
函数参数的声明
1 2 3 4 5 6 7 8 9 10
functionadd(a: number, b: number, ratio?: number) { // ?表示参数可选 console.log(ratio) ratio = ratio || 0.6 return a + b } functionadd(a: number, b: number, ratio: number = 0.6) { // 设置默认值后不需要使用? console.log(ratio) ratio = ratio || 0.6 return a + b }