ts学习日记02 function

101 阅读1分钟
// 指定参数类型
function addNumbers(a: number, b: number): number {
    return a + b
}

export default addNumbers

export const addStrings = (str1: string, str2: string) => `${str1}${str2}`
// 联合类型
export const format = (title: string, params: string | number) => `${title}${params}`
// void 不会返回数据
export const printFormat = (title: string, params: string | number): void => {
    console.log(format(title, params));
}
// resolve 抛出的是一个字符串
export const fetchData = (url: string): Promise<string> => Promise.resolve(`Data fetch ${url}`)

function introduce(salutation: string, ...names: string[]): string {

    return `${salutation} ${names.join(" ")}`
}

export function getName(user: { first: string; last: string }): string {
    //  ?? 默认输出
    return `${user?.first ?? 'first'},${user?.last ?? 'last'}`
}
// 回调函数
export function printToFile(text: string, callback: () => void): void {
    console.log(text);
    callback()
}

// 回调函数类型
type MutationFunction = (v: number) => number
// 回调函数类型
export function arrayMutate(numbers: number[], mutate: MutationFunction): number[] {
    return numbers.map(mutate)
}
const myMutationFunction: MutationFunction = (a: number) => a //返回a
console.log(arrayMutate([1, 2, 3], (v) => v * 10));
type adderFunction = (val: number) => number
// 返回值是一个函数
export function createAdder(num: number): adderFunction {
    return (val: number) => num + val
}
const addOne = createAdder(1)
console.log(addOne(2));