TS系列之typeof

TS系列之typeof

前言

今天总结一下typeof相关的知识。
typeof在Js中也是常用来判断变量类型的关键字,那么在Ts中的作用又是什么,下面一起来看看。

回顾:Js中typeof的用法

1、typeof的返回类型有哪些

  • “undefined”
 typeof undefined
  • “object”
 typeof null
 或者其他任意对象

至于null为什么返回的类型是object可以参考这篇文章:typeof null is ‘object’

  • “boolean”
typeof true
  • “number”
typeof 1
  • “bigint”
 typeof BigInt(1)
  • “string”
 typeof ""
  • “symbol”
 typeof Symbol(1)
  • “function”
 typeof function a () {
    
    }

Ts 中的 typeof 运算符作为类型判断的工具

什么是 typeof?

typeof 是 TypeScript 中的运算符,用于获取给定表达式的类型。返回一个表达式类型的字符串。

一个简单的例子:

const num = 1;
const str = "Hello";
console.log(typeof num); // 输出 "number"
console.log(typeof str); // 输出 "string"

在这个例子中,typeof num 返回 “number”,而 typeof str 返回 “string”,很明显这和js中没有什么区别。

类型保护与条件类型

typeof 运算符的真正强大之处在于它与条件类型的结合使用。通过将 typeof 与条件类型结合,我们可以在运行时对不同类型的代码进行条件分支。
举个例子:
比如我们想要实现一个函数,将传入的数字或者字符串类型的数据自增1并返回

function test (num: number | string): number | string {
    
    
  return num++
}
//这时候ts报错,提示:An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.
//意思是:算术操作数的类型必须是“any”、“number”、“bigint”或枚举类型

这个时候typeof就可以派上用场,改造如下:

function test (num: number | string): number | string {
    
    
  if (typeof num === 'number') {
    
    
    return ++num;
  } else {
    
    
    return +num + 1;
  }
}

复杂类型

typeof 判断复杂类型时和js中的用法一样"object"、“function”、“symbol” 等等。
接下来我们看一下实际在开发中用的场景:
1、例如我们有个对象,如果对象嵌套深或者对象属性较多时,那么你就可以直接用tyoeof来获取这个对象的属性中的所有类型。

const appconfig = {
    
    
  id: '1',
  text: 'app',
  appName: 'app',
  appImg: 'https://app',
  appType: 'app',
  positionNum: 1,
  url: 'https://app'
}

type appType = typeof appconfig
type appType = {
    
    
    id: string;
    text: string;
    appName: string;
    appImg: string;
    appType: string;
    positionNum: number;
    url: string;
}
const appconfigtest: appType = {
    
    }
//所以你就可以直接用appType来约束新定义对象appconfigtest

2、也可以获取对象中单个属性的类型

type appType = typeof appconfig.appImg
//type appType = string

3、当我想要通过函数创建并获取类的实例,那么就可以通过typeof获取到class构造函数的类型

class APP {
    
    
  name: string;
  img: string;
  constructor (name: string, img: string) {
    
    
    this.name = name;
    this.img = img;
  }
}
//(parameter) CP: new (name: string, img: string) => APP
function createApp(CP: typeof APP, name: string, img: string) {
    
    
  return new CP(name, img);
}

总结

到这里我们就基本了解了typeof在ts中常见的一些用法, 其它用法还需继续探索,分享学习。

猜你喜欢

转载自blog.csdn.net/qq_43205326/article/details/133466714