# 映射类型

类似于 js 中数组的 map 方法,将一个数组映射为另一个数组

映射类型建立在索引签名的语法上,索引签名用于声明没有提前声明的属性类型:

type OnlyBoolsAndHorses = {
  [key: string]: boolean | Horse;
};

const conforms: OnlyBoolsAndHorses = {
  del: true,
  rodney: false,
};

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

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

然后试一下

type FeatureFlags = {
  darkMode: () => void;
  newUserProfile: () => void;
};

type FeatureOptions = OptionsFlags<FeatureFlags>;

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

# 映射修饰符

  • readonly 影响映射后的可变性
  • ? 影响映射后的可选性

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

移除 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 重新映射 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;
// };

Capitalize 和 模板字符串类型 将会再后面涉及

还可以过滤掉不要的 key

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

# 进一步探讨

使用条件类型来修改 key 的类型

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