TypeScript Mapped Types All in One


TypeScript Mapped Types All in One

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

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


// in keyof, Object Type ?
type OptionsFlags = {
  [Property in keyof Type]: boolean;
};

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

// Type 是对象类型
const conforms2: OptionsFlags<{}> = {
  del: true,
  rodney: false,
};

Mapping Modifiers

readonly and ?

- or +


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

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

as

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


type Getters = {
    [Property in keyof Type as `get${Capitalize}`]: () => Type[Property]
};
 
interface Person {
    name: string;
    age: number;
    location: string;
}
 
type LazyPerson = Getters;

never


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



type EventConfig = {
    [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

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

https://www.typescriptlang.org/docs/handbook/2/mapped-types.html

refs

https://www.typescriptlang.org/docs/handbook/2/types-from-types.html

https://www.typescriptlang.org/docs/handbook/2/conditional-types.html

https://www.typescriptlang.org/docs/handbook/2/indexed-access-types.html

https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!