这是我参与「第五届青训营 」笔记创作活动的第11天
函数之间的兼容性
函数之间兼容性比较复杂,需要考虑:
- 参数个数
- 参数类型
- 返回值类型
①参数个数:参数多的兼容参数少的(或者说,参数少的可以赋值给多的)
type F1 = (a: number) => void
type F2 = (a: number, b: number) => void
let f1:F1
let f2: F2 = f1
- 参数少的可以赋值给参数多的,所以,f1可以赋值给f2。
- 数组forEach方法的第一个参数是回调函数,该示例中类型为:(value: string,index: number, array: string0)=>void。
- 在JS中省略用不到的函数参数实际上是很常见的,这样的使用方式,促成了TS中函数类型之间的兼容性。
- 并且因为回调函数是有类型的,所以,TS会自动推导出参数item、index、array的类型。
②参数类型:相同位置的参数类型要相同(原始类型)或兼容(对象类型)
type F1 = (a: number)
=> string type F2 = (a: number) => string let f1: F1
let f2: F2 = f1
函数类型F2兼容函数类型F1,因为F1和F2的第一个参数类型相同。
interface Point2D { x: number; y: number }
interface Point3D { x: number; y:number; z: number }
type F2 = (p: Point2D) => void
type F3 = (p: Point3D) => void
let f2: F2
let f3: F3 = f2
- 此处与前面讲到的接口兼容性冲突。
- 技巧:将对象拆开,把每个属性看做一个个参数,则,参数少的(f2)可以赋值给参数多的(f3)
③返回值类型:只关注返回值类型本身即可:
type F5 =O => string
type F7 =()=> { name: string }
type F6 =(
string
type F8= ()=> { name: string; age: number }
let f5: F5
let f7:F7
let f6: F6 = f5
let f8:F8
f7 =f8
- 如果返回值类型是原始类型,此时两个类型要相同,比如,左侧类型F5和F6
- 如果返回值类型是对象类型,此时成员多的可以赋值给成员少的,比如,右侧类型F7和F8