01-函数间ts的交互使用
1. 回调函数
typescript
function printToFile(text: string, callback: () => void) {
console.log(text)
callback()
}
printToFile('print to file', () => {})进行类型的抽取, 这样可以便于后面统一管理
typescript
// mutate回调函数进行数据处理
function arrayMutate(array: number[], mutate: (v: number) => number): number[] {
return array.map(mutate)
}
const array1 = arrayMutate([1, 20, 3], v => v * 10)
console.log(array1)
// 定义相关类型
type MutateFunction = (v: number) => number
// const myNewMutateFunction = (v: number) => v * 100
function arrayMutate2(array: number[], mutate: MutateFunction): number[] {
return array.map(mutate)
}2. 配合闭包使用
typescript
type MutateFunction = (v: number) => number
function addNumber(target: number): MutateFunction {
return (value: number) => value + target
}
const addOne = addNumber(1)
console.log(addOne(50))