特定の型のプロパティだけ取り出す
関数
type PickPropsWithType<T, TYPES> = {
[P in { [K in keyof T]: T[K] extends TYPES ? K : never }[keyof T]]: T[P]
};
実装例
例えば、MUIでPalette
はこのように定義されている。
export interface Palette {
common: CommonColors;
mode: PaletteMode;
contrastThreshold: number;
tonalOffset: PaletteTonalOffset;
primary: PaletteColor;
secondary: PaletteColor;
error: PaletteColor;
warning: PaletteColor;
info: PaletteColor;
success: PaletteColor;
grey: Color;
text: TypeText;
divider: TypeDivider;
action: TypeAction;
background: TypeBackground;
getContrastText: (background: string) => string;
augmentColor: (options: PaletteAugmentColorOptions) => PaletteColor;
}
ここから、PaletteColor
のみ取り出すようにするには、
type paletteColors = keyof PickPropsWithType<Palette, PaletteColor>
とすると、paletteColorsは、"primary" | "secondary" | "error" | "warning" | "info" | "success"
のユニオン型となる