[ts]typescript高阶之typeof使用

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前端必备工具推荐网站(免费图床、API和ChatAI等实用工具):
http://luckycola.com.cn/

前言

学习目标
1、typeof与对象结合使用
2、typeof与枚举结合使用
3、typeof与class类结合使用
4、const断言的使用


一、typeof与对象结合使用

代码如下(示例):

let lolo = {
    
    
  name: 'zhanhsan',
  age: 18,
  child: {
    
    
    name: 'zhangsansan',
    like: true,
    age: 12
  }
};

type Lolo = typeof lolo;
// {
    
    
//   name: string;
//   age: number;
//   child: {
    
    
//       name: string;
//       like: boolean;
//       age: number;
//   };
// }

type Lolochild = typeof lolo.child;
// {
    
    
//   name: string;
//   like: boolean;
//   age: number;
// }

二、typeof与枚举结合使用

代码如下(示例):

enum HttpMethod {
    
    
  Get,
  Post
};

// 注意枚举类型之间的转换关系 如下
// 上面ts枚举类型写法等价于es5中的写法:
// "strict"
// var HttpMethod;
// (function (HttpMethod) {
    
    
//   HttpMethod[HttpMethod['Get' = 0]] = 'Get';
//   HttpMethod[HttpMethod['Post' = 1]] = 'Post';
// })(HttpMethod || HttpMethod = {});


type Methods = typeof HttpMethod;
const meth: Methods = {
    
    
  Get: 0,
  Post: 1
}

type Meth = keyof typeof HttpMethod;//  "Get" | "Post"

三、typeof与class类结合使用

代码如下(示例):

class Ponit {
    
    
  x: number;
  y: number;
  constructor(x: number, y: number) {
    
    
    this.x = x;
    this.y = y;
  }
};

// 工厂函数
// 这里 typeof Point ------> new (x: number, y: number) => number;
function getInstance(PointClass: typeof Ponit, x: number, y: number) {
    
    
  return new PointClass(x, y);
}
// 下面写法将报错
function getInstance2(PointClass: Ponit, x: number, y: number) {
    
    
  return new PointClass(x, y);// 报错 此表达式不可构造。类型 "Ponit" 没有构造签名。
}

四、typeof与函数结合使用

代码如下(示例):

//  typeof与函数结合使用
function add(a: number, b: number): number {
    
    
  return a + b;
};

type AddType = typeof add;//  (a: number, b: number) => number
type AddReturnType = ReturnType<AddType>;// number
type AddParamsType = Parameters<AddType>;// [a: number, b: number]

五、const断言的使用

代码如下(示例):


// 5 const断言可以是类型推断更加准确
let requestMethod = 'get'; // string
let requestMethod2 = 'get' as const; // "get"
let requestMethod3 = <const>'get'; // "get"

let user9 = {
    
    
  id: 333,
  name: 'lisi'
}

type User9 = typeof user9;
// {
    
    
//   id: number;
//   name: string;
// }



let user92 = {
    
    
  id: 333,
  name: 'lisi'
} as const;
type User92 = typeof user92;
// {
    
    
//   readonly id: 333;
//   readonly name: "lisi";
// }


总结

猜你喜欢

转载自blog.csdn.net/qq_48896417/article/details/125270242
今日推荐