学习呦
14 10月 2025 3 min read

类型操作关键字

Written by 米豆

keyof

用于类型对象,可以拿到类型对象的key,作为一个新类型。所以=号左边必须为一个类型变量,或者可以是typeof

type Point = { x: number; y: number };
type P = keyof Point;
// type P = "x" | "y"

P变量相当于一个字面量类型

type Mapish = { [k: string]: boolean };
type M = keyof Mapish;

// type M = string | number

如果key为索引签名,那么keyof将返回这个签名的类型来替代key

typeof

js中也有typeof关键字,可以返回一个变量的类型

一般来讲,typeof和keyof来联合使用,可以获取到一个对象属性的字面量类型

const Features = {
darkMode: () => {},
newUserProfile: () => {}
};

type FooFeatureType = keyof typeof Features
// type FooFeatureType = "darkMode" | "newUserProfile"

官方的handbook有一个易错的提示

如果想获得一个函数Function的类型,并不是直接拿函数名作为类型的,而是要用typeof关键字

function f() {
return { x: 10, y: 3 };
}
type P = ReturnType<f>; // 这是错的❌
// 'f' refers to a value, but is being used as a type here. Did you mean 'typeof f'?

// 应该这样写
type P = ReturnType<typeof f>;
↑