Open2

【TypeScript】便利な自作utility types

yjunyayjunya

概要

ユニオン型におけるPick
Extractと違いUに指定する型はTの要素しか受け付けないが,補完が効くので便利.

定義

type UnionPick<T, U extends T> = U;

使用例

sample.ts
type A = "A" | "B" | "C";

type B = UnionPick<A, "A" | "B">;
type C = UnionPick<A, "D">; // error: Type '"D"' does not satisfy the constraint 'A'
yjunyayjunya

概要

readonlyなRecord

定義

type ReadonlyRecord<K extends keyof any, T> = {
  readonly [P in K]: T;
};

使用例

sample.ts
type A = "hoge";
const a: ReadonlyRecord<A, string> = {
    "hoge": "ほげ",
};
const b: Record<A, string> = {
    "hoge": "ほげ"
};
a.hoge = "ふが"; // error: Cannot assign to 'hoge' because it is a read-only property.
b.hoge = "ふが";