• 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}


  • 相关阅读:
    IEEE754二进制浮点数算术标准
    符号三角形代码勘误
    最近点对问题
    【Unsolved】线性时间选择算法的复杂度证明
    解决mosh: Nothing received from server on UDP port 60001 环境: centos7.1
    半导体测试基础
    python进程------multiprocessing包
    python线程------queue、生产者和消费者模式
    pyhon——线程同步条件(event)
    os 模块
  • 原文地址:https://www.cnblogs.com/wzndkj/p/12976244.html
Copyright © 2020-2023  润新知