zoukankan      html  css  js  c++  java
  • 【学习笔记】TypeScript typeof 操作符

    【学习笔记】TypeScript typeof 操作符

    原文:http://www.semlinker.com/ts-typeof/

    在TypeScript中,typeof操作符可以用来获取一个变量或对象的类型。

    interface Person {
        name: string;
        age: number;
    }
    
    const sem: Person = { name: "semlinker", age: 30}
    type Sem = typeof sem; // type Sem = Person

    在上面代码中,我们通过typeof操作符获取sem变量的类型并赋值给Sem类型变量,之后我们就可以使用Sem类型:

    const lolo: Sem = { name: "lolo", age: 5 }

    你也可以对嵌套对象执行相同的操作:

    const kakuqo = {
        name: "kakuqo",
        age: 30,
        address: {
            province: '福建',
            city: '厦门'
        }
    }
    
    type Kakuqo = typeof kakuqo;
    /**
     * type Kakuqo = {
     *  name: string;
     *  age: number;
     *  address: {
     *   province: string;
     *   city: string;
     *  }
     * }
     */

    此外,typeof操作符除了可以获取对象的结构类型之外,它也可以用来获取函数对象的类型,比如:

     function toArray(x: number): Array<number> {
         return [x]
     }
    
     type Func = typeof toArray; // -> (x: number) => number[]
  • 相关阅读:
    python 对比学习
    支付宝
    springboot logback
    ngnix学习视频
    node学习
    puppeteer 相关知识
    Dota2App--第三天
    Dota2APP--第二天
    Dota2APP--第一天
    iOS ---进阶之摇一摇
  • 原文地址:https://www.cnblogs.com/cathy1024/p/14030761.html
Copyright © 2011-2022 走看看