iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐱

Creating a Function to Apply Branded Types to All Object Properties in TypeScript

に公開
2023/06/28
1件

Conclusion

export const withBrand = <T extends { [k: string]: unknown }, B extends string>(obj: T, brand: B) => {
  return obj as Record<keyof T, T[keyof T] & { __Brand: typeof brand }>;
};

Explanation

Type Parameter <T extends { [k:string] unknown }, B extends string>

Here, two type parameters T and B are defined. T accepts an object type. B represents the type of the brand (unique identifier).

Function Parameters (obj: T, brand: B)

The function has two parameters. obj is the object to be branded, and brand is the brand itself.

Function Return Value Record<keyof T, T[keyof T] & { __Brand: B }>

This function returns a new object that retains the properties of the original object while adding a brand property __Brand to each property. This __Brand property has the type typeof brand of the original brand brand.
Type parameters T and B are used, but these are directly inferred from the function parameters obj and brand.

Situations where this function is useful

This function is useful when you want to notify the type system that a specific object plays a specific role. For example, you can make it so that a certain function only accepts objects of a specific brand as arguments.

That's it!

Discussion

nap5nap5

これ便利ですね。ぼくもちょっとデモつくってみました。

https://codesandbox.io/p/sandbox/jovial-ptolemy-nwlrkv?file=%2Fsrc%2Findex.ts%3A7%2C16

定義側

import { match } from "ts-pattern";
import { Entries } from "type-fest";
import { dequal } from "dequal";

// @see https://zenn.dev/sho_ts/articles/9dcd30f593c0f3
export const withBrand = <T extends {}, B extends string>(obj: T, brand: B) =>
  obj as Record<keyof T, T[keyof T] & { __Brand: B }>;

const UploadStatusPattern = {
  INITIAL: {
    name: "INITIAL",
    value: 1,
  },
  PREPARED: {
    name: "PREPARED",
    value: 2,
    salt: "hoge",
  },
  UPLOADING: {
    name: "UPLOADING",
    value: 3,
  },
  UPLOADED: {
    name: "UPLOADED",
    value: 4,
  },
  UPLOAD_ERROR: {
    name: "UPLOAD_ERROR",
    value: 5,
  },
} as const;

const UploadStatusData = (
  Object.entries(UploadStatusPattern) as Entries<typeof UploadStatusPattern>
).map(([key, data]) => data);

type UploadStatus = (typeof UploadStatusData)[number];

export const getCurrentUploadStatus = (uploadStatus: UploadStatus) => {
  return match(uploadStatus)
    .with({ name: "INITIAL" }, (data) => data)
    .with({ name: "PREPARED" }, (data) => data)
    .with({ name: "UPLOADING" }, (data) => data)
    .with({ name: "UPLOADED" }, (data) => data)
    .with({ name: "UPLOAD_ERROR" }, (data) => data)
    .exhaustive();
};

export const UPLOAD_STATUS = withBrand(UploadStatusPattern, "UploadStatus");

type BrandedUploadStatus = (typeof UPLOAD_STATUS)[keyof typeof UPLOAD_STATUS];

export const isUploading = (uploadStatus: BrandedUploadStatus) =>
  dequal(uploadStatus, UPLOAD_STATUS.UPLOADING);

使用側

import { test, expect } from "vitest";
import { UPLOAD_STATUS, getCurrentUploadStatus, isUploading } from ".";

test("[1]", () => {
  const result = isUploading(UPLOAD_STATUS.UPLOADING);
  expect(result).toStrictEqual(true);
});

test("[2]", () => {
  const result = isUploading(UPLOAD_STATUS.PREPARED);
  expect(result).toStrictEqual(false);
});

test("[3]", () => {
  const result = getCurrentUploadStatus(UPLOAD_STATUS.PREPARED);
  if (result.name === "PREPARED") {
    expect(result.salt).toStrictEqual("hoge");
  }
});

簡単ですが、以上です。

1