Open2
【TypeScript】便利な自作utility types
![yjunya](https://res.cloudinary.com/zenn/image/fetch/s--__ZEtTYl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_70/https://storage.googleapis.com/zenn-user-upload/avatar/710dec7e51.jpeg)
概要
ユニオン型における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'
![yjunya](https://res.cloudinary.com/zenn/image/fetch/s--__ZEtTYl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_70/https://storage.googleapis.com/zenn-user-upload/avatar/710dec7e51.jpeg)
概要
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 = "ふが";