映射类型

当您不想重复自己时,有时一种类型需要基于另一种类型。

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

type Horse = {};
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 OptionsFlags<Type> = {
  [Property in keyof Type]: boolean;
};
type FeatureFlags = {
  darkMode: () => void;
  newUserProfile: () => void;
};

type FeatureOptions = OptionsFlags<FeatureFlags>;

映射修饰符

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

cflIjIwfza+ItolNv1ZAE7n3mDzIOe5p8LOu4FAtXT+q/hKycPDGF/Gdhgak4pDYhSrb7dG/pDIPvEn4kXLBQ6tUdpbc6fH8w71d7ZXSgrmJstRg8oJ/nDjbEYK63hNr0cFzqOz/o81gxbl2TtQ76byxBB4FNU3EtXBYRXDXIuXQNZ14AptkL6IcQV39jP9r+vPOFgVznEXQIyhREQSyOg==

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

通过 as 重新映射键

7MDYQn3qF7fFb7GB32/CERKG02nQS2PJ7NnTKs2MyjMnL9TpHQ314PriYX1PBmCrwadzJYsQd6Sp8YgLgwOZtTiF+IxAgAJVDZu7EhK7HmDZFej4ig/5lG8tvbJXAG1CRyXP5EvfcLTVqUMBlk00vaLlQeQUAoihCdOizqjDENTeMpczXreHxsg0lB7aH7fG

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

mQZcnIqaFo5ztwB3yxXpFZjmmBfX/9UyGECqju514GrkUmWnbHLoaThM+kifFFAHW8CcOysmOddL8Z70IxRxtTH0mnIXojN2A+dpbNYNBkIuaJ2EHE22v4//tFriMh+gE2vBwKihQ8zTIg21XeXyw69pfAsRDFXfppBiwt60J9ubn8gqY8SVwtHtRC6LGZ0G6YoN2llwqofr3QEbzR+J6A==

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

cflIjIwfza+ItolNv1ZAE/A2gsDU/KbUNlz1SP0k3ocfKU+O/sJzUyVTzSwiz1vxtS+H0Y34cK4Q/t0imviy6+WEBPQMKKKCItplZQ3tyYs=

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

OM56NII7rHdv4MLZZ1UfAz9aX9lsm29760pjz+fN6I5VZaa+u59FuFJhmX5AGTXrwSJ/AsP6UNBHJrlc+Vpqspyq05r4IzIRhmEEsZgXO7VF/rXAkawUgCfMJlo+Za9ew7Dbz9q7ZjoyWjdl81Isr9r+r4o6uDHhWs+qZ9TfsAr0/Qw/h0BnmF3Op+EdRGuz

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>

进一步探索

Rdy9nymJfOZcqYEihEYL1KUVRh7ZRUGCty5F6D5fc9TpEutvB3f6iFTyUN3h9QzTxvT1IPVBIox/wj96mCN0QD2fGHJ5cK5KnNyuBlKVgBZzPDYtO0ZcMCOV3MGghTgPiDHVb4pCKqDHwHuJXSlNYUtO1a/xllRYsPE/Ap/Ls6B33QoPamIcnWJwB5L2L2G+p9SGp9kATy606uC3KDstz2H1GYwyVIOkF6oStheP6E+kSthfaKg0ZMtoa0WdzIrHlBlR05sWik3FTaSnSC5DDj+rGX3Nnf6a4fYOpYxPVJrfYBrr7ArFoVo7VuYxyBruNECrwO1QxTnLqdnYZLoKrpRvvH3Qjz4oRnP1EEZiw2yBttc71+y0mLAXrkOsy5WKf2aiBgkHm53m7eMuyWsUgZfpcE9f25REj7VaS3QP018=

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