Skip to content
Published at:

Typeof Type Operator

JavaScript 本身就有 typeof 操作符,你可以在表达式上下文中(expression context)使用:

ts
// Prints "string"
console.log(typeof 'Hello world');

而 TypeScript 添加的 typeof 方法可以在类型上下文(type context)中使用,用于获取一个变量或者属性的类型。

ts
let s = 'hello';
let n: typeof s;
// let n: string

配合ReturnType<T>

Predicate 是类型

ts
type Predicate = (x: unknown) => boolean;

type Pre = ReturnType<Predicate>;
// type Pre = boolean

predicate是值,需要配置 typeof操作符

ts
function predicate(x: unknown): boolean {
  return false;
}

type Pre1 = ReturnType<typeof predicate>;
// type Pre1 = boolean

typeof 只能对标识符和属性使用

ts
// Meant to use = ReturnType<typeof msgbox>
let shouldContinue: typeof msgbox("Are you sure you want to continue?"); // Error

type RetType =  ReturnType<typeof msgbox>

对象使用 typeof

ts
const person = { name: 'kevin', age: '18' };
type Kevin = typeof person;

// type Kevin = {
// 		name: string;
// 		age: string;
// }

函数使用 typeof

ts
function identity<Type>(arg: Type): Type {
  return arg;
}

type result = typeof identity;
// type result = <Type>(arg: Type) => Type

enum 使用 typeof

在 TypeScript 中,enum 是一种新的数据类型,但在具体运行的时候,它会被编译成对象。

ts
enum UserResponse {
  No = 0,
  Yes = 1,
}

对应编译的 JavaScript 代码为:

typescript
var UserResponse;
(function (UserResponse) {
  UserResponse[(UserResponse['No'] = 0)] = 'No';
  UserResponse[(UserResponse['Yes'] = 1)] = 'Yes';
})(UserResponse || (UserResponse = {}));

如果我们打印一下 UserResponse

ts
console.log(UserResponse);

// [LOG]: {
//   "0": "No",
//   "1": "Yes",
//   "No": 0,
//   "Yes": 1
// }

而如果我们对 UserResponse 使用 typeof

ts
type result = typeof UserResponse;

// ok
const a: result = {
  No: 2,
  Yes: 3,
};

// result 类型类似于:
// {
//	"No": number,
//  "YES": number
// }

不过对一个 enum 类型只使用 typeof 一般没什么用,通常还会搭配 keyof 操作符用于获取属性名的联合字符串:

ts
type result = keyof typeof UserResponse;
// type result = "No" | "Yes"