学习呦
14 10月 2025 3 min read

映射类型 Mapped types

Written by 米豆

得和“索引签名”配合,在不知道一个对象类型有哪些key的前提下,注意⚠️,这里指的是类型,而不是值

要从另外一个类型拿到key

type OptionsFlags<Type> = {
[Property in keyof Type]: boolean;
};

这里有点复杂,Type是一个对象类型,OptionsFlags类型的key是由Type这个类型决定的,Type有什么key,OptionsFlags就有什么key

这样做的好处就是,我们拆分出了key,但给key赋予的value的类型可以不同,比如说原来的Type里面value的类型为Function,新映射出来的类型可以为boolean

关键在于in keyof

还有一个用途的例子

type MappedTypeWithNewProperties<Type> = {
[Properties in keyof Type as NewKeyType]: Type[Properties]
}

这里多了as关键字,意思是可以把key换一个名字

type Getters<Type> = {
[Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};

interface Person {
name: string;
age: number;
location: string;
}

type LazyPerson = Getters<Person>;

// type LazyPerson = {
// getName: () => string;
// getAge: () => number;
// getLocation: () => string;
//}

上面的例子Person类型映射的新类型LazyPerson,把Person的key重命名为了getter方法的名字

↑