0%

TypeScript中的typeof

在之前的文章中,介绍过JavaScript的typeof运算符。在JavaScript中typeof主要是用于类型检测。
而在TypeScript中typeof不光能类型检测,还能用来获取类型。
具体是什么,得结合环境来看。
举一个简单地例子

1
2
3
let bar = { a: 0 }
let b = typeof bar // "object"
type c = typeof bar // "{a: number}"

我们可以看出来,如果typeof赋值给一个变量的话,那将用JavaScript运算符。 如果赋给一个type的话,就是获取它的类型。TypeScript将其对象中的a属性自动推断为number类型。

也可以获取类型通过一个字符数组

1
2
3
const data = ['text 1', 'text 2'] as const;
type Data = typeof data[number];
// type Data = "text 1" | "text 2"

或者是一个tuple

1
2
3
4
5
6
export type Lit = string | number | boolean | undefined | null | void | {};
export const tuple = <T extends Lit[]>(...args: T) => args;

const animals = tuple('cat', 'dog', 'rabbit', 'snake');
type Animal = (typeof animals)[number];
//'cat' | 'dog' | 'rabbit' | 'snake'

还可以与keyof结合,将对象的key转为联合类型。

1
2
3
4
5
6
7
const datas = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
}
type data = keyof typeof datas;
// type data = "key1" | "key2" | "key3"