TypeScript - 映射类型

当你不想重复自己的时候,有时一个类型需要基于另一个类型。映射类型建立在索引签名的语法基础上,用于声明尚未提前声明的属性类型:

type OnlyBoolsAndHorses = {
  [key: string]: boolean | Horse;
};
 
const conforms: OnlyBoolsAndHorses = {
  del: true,
  rodney: false,
};

映射类型是一种泛型类型,它使用PropertyKey的联合(通常通过keyof创建)来遍历键以创建类型:

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

在这个例子中,OptionsFlags将从类型Type中获取所有属性,并将它们的值更改为布尔值。

type Features = {
  darkMode: () => void;
  newUserProfile: () => void;
};
 
type FeatureOptions = OptionsFlags<Features>;

//  结果           
type FeatureOptions = {
    darkMode: boolean;
    newUserProfile: boolean;
}

映射修改器

有两个附加的修饰符可以在映射过程中应用:readonly和它们分别影响可变性和可选性。

您可以通过添加前缀-或+来删除或添加这些修饰符。如果不添加前缀,则假定为+

// Removes 'readonly' attributes from a type's properties
type CreateMutable<Type> = {
  -readonly [Property in keyof Type]: Type[Property];
};
 
type LockedAccount = {
  readonly id: string;
  readonly name: string;
};
 
type UnlockedAccount = CreateMutable<LockedAccount>;

// 结果
type UnlockedAccount = {
    id: string;
    name: string;
}
// Removes 'optional' attributes from a type's properties
type Concrete<Type> = {
  [Property in keyof Type]-?: Type[Property];
};
 
type MaybeUser = {
  id: string;
  name?: string;
  age?: number;
};
 
type User = Concrete<MaybeUser>;

// 结果    
type User = {
    id: string;
    name: string;
    age: number;
}

通过 as重映射

在TypeScript 4.1及以后版本中,你可以在映射类型中使用as子句重新映射映射类型中的键:

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

您可以利用模板文字类型等功能从以前的属性名创建新的属性名:

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;
}

你可以使用never通过条件类型来过滤键:

// Remove the 'kind' property
type RemoveKindField<Type> = {
    [Property in keyof Type as Exclude<Property, "kind">]: Type[Property]
};
 
interface Circle {
    kind: "circle";
    radius: number;
}
 
type KindlessCircle = RemoveKindField<Circle>;

// 结果           
type KindlessCircle = {
    radius: number;
}

您可以映射任意的联合,而不仅仅是 string | number | symbol,但任何类型的联合:

type EventConfig<Events extends { kind: string }> = {
    [E in Events as E["kind"]]: (event: E) => void;
}
 
type SquareEvent = { kind: "square", x: number, y: number };
type CircleEvent = { kind: "circle", radius: number };
 
type Config = EventConfig<SquareEvent | CircleEvent>

// 结果
type Config = {
    square: (event: SquareEvent) => void;
    circle: (event: CircleEvent) => void;
}

进一步探索

映射类型与此类型操作部分中的其他功能配合良好,例如,这里是一个使用条件类型的映射类型,该类型返回truefalse,这取决于对象是否将属性pii设置为 true

type ExtractPII<Type> = {
  [Property in keyof Type]: Type[Property] extends { pii: true } ? true : false;
};
 
type DBFields = {
  id: { format: "incrementing" };
  name: { type: string; pii: true };
};
 
type ObjectsNeedingGDPRDeletion = ExtractPII<DBFields>;

// 结果
type ObjectsNeedingGDPRDeletion = {
    id: false;
    name: true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值