Skip to content

typeof 数据类型判断

JavaScript中也存在typeof关键字,那么在TS中的typeof有啥区别

在JavaScript中typeof主要用来判断数据类型,其语法结构如下

js
typeof obj === "object";

那么在TypeScript中typeof有啥区别?

ts
// 直接获取已有变量的类型 ,不需要自己去重新声明变量类型了
type Obj = typeof obj;

image-20230213145943450

typeof 与 基本数据类型

js
const bool = true;
const num = 12;
const nu = null;
const undef = undefined;
type Bool = typeof bool;     // true
type Num = typeof num;       // 12
type Nul = typeof nu;        // any
type Undef = typeof undef;   // any

const symb:Symbol = Symbol("12");
const symb1 = Symbol("12");
type Symb = typeof symb;   // Symbol
type Symb1 = typeof symb1;   // typeof symb1

需要注意的是:

  1. 对于 Null 或者 Undefined 类型的变量,typeof的结果为 any
  2. 对于 Symbol 类型的变量,typeof的结果为 typeof xxx;

typeof 与 枚举类型

js
enum UserType {
  Admin,
  Seat,
  TL
}

type UserTypeKey = typeof UserType

typeof 与 class类

js
class Anmial {
  name : string;
  constructor(name:string){
    this.name = name;
  }
}

let animal : Animal  
let animal1 : typeof Animal
  1. Animaltypeof Animal 的区别
  • Animal 代表变量是一个Animal类型的实例对象( new Animal() )
  • typeof Animal 代表变量是一个Animal类型( Animal )
js

function getInstance(aninal : Animal , name : string) : Animal {
  animal.name = name
  return animal
}

function getInstance(aninal : typeof Animal , name : string) : Animal {
  return new Animal(name)
}

typeof 和 函数

js
// (aninal : Animal , name : string ) => Animal
type GetIntance = typeof getInstance;

// 获取函数返回体类型
type GetIntanceResult = ReturnType<typeof getIntance>
type GetIntanceResult1 = ReturnType<GetIntance>

// 获取函数的入参类型
type GetIntanceParamsType = Parameters<typeof getIntance>;// [aninal : Animal , name : string]
type GetIntanceParamsType1 = Parameters<GetIntance>;// [aninal : Animal , name : string]