TypeScript 函数相关类型

// JS 中定义函数的方式
function hell(){}
const hello1 = function(){}
const hello2 = () => {}
// TS 中定义函数的方式
// 参数需要类型注解,返回值不需要
function add(first: number, second: number) { 
    return first + second;
}
const total = add(1,2); // 这里 total 是3,肯定是 number


// 在返回值不小心写错了,这个时候不报错
function add1(first: number, second: number) { 
    return first + second + '';
}
const total1 = add1(1, 2); // 这里 total 推断出来是 string


// 但是实际上是想要 total 是 number 类型的,这个时候加上返回值的限制,就会报错
function add2(first: number, second: number): number { 
    return first + second + ''; // Type 'string' is not assignable to type 'number'.
}
const total2 = add2(1, 2);

总结:明确了需要的返回值类型,可以做一层约束



function add(first: number, second: number): number { 
    return first + second;
}
// 函数返回值除了这种基本类型,还有两种

/**
 * 1、函数的返回值是 void 类型,也就是希望这个函数没有返回值
 * 如果有返回值就会报错
 */
function sayHello(): void {
    console.log('hello');
}

/**
 * 2、函数的返回值是 never 类型,never 的意思是这个函数永远不可能执行到最后
 * 比如 throw 后面的代码没有办法执行,也就是这个函数永远不可能执行完成
 * 或者 while(true){} 这也永远执行不完
 */
function errorEmitter(): never {
    throw new Error();
    console.log(123);
}

总结: void (这个函数没有返回值), never (这个函数永远不可能执行到最后)





// 传统的 js 传递参数的方法,这里面用的是解构的方式

function add ({first, second}) {
    return first + second
}
const total = add({first:1, second:2});

/**
 * 这个时候我想这个参数是有类型的,那么解构的方式要怎么进行
 * {first, second} : {first:number, second:number} 是正确的结构声明类型的方式
 */
function add1 ( 
    {first, second} : {first:number, second:number} 
): number {
    return first + second
}
const total1 = add1({first:1, second:2});


/**
 * 在只有一个解构数的时候
 * { first }: number 不能这么写
 * { first }: {first: number} 要这么写,统一的 {}:{}
 */
function getNumber({ first }: {first: number}){
    return first;
}
const count = getNumber({ first: 1 })
总结:ts 结构参数传递方式 {first, second} : {first:number, second:number}