[Typescript] Indexing an Object with Branded Types

In this exercise, we're going to look at a really interesting property of branded types when they're used with index signatures.

Here we have our User and Post interfaces, along with PostId and UserId branded types:

Down in the tests we create entries in our database based on db[postId] and db[userId]:

const postId = "post_1" as PostId;
const userId = "user_1" as UserId;

db[postId] = {
  id: postId,
  title: "Hello world",
};

db[userId] = {
  id: userId,
  name: "Miles",
};

But there's a problem!

With the current implementation of db, we are unable to directly get a user or post by id:

const db: Record<string, User | Post> = {};

Whether we want a UserId or PostId, the result will be User | Post:

// hovering over result const result = db['123123'] // displays const result: User | Post
// hovering over result
const result = db['123123']

// displays
const result: User | Post

 

Solution:

const db: {
  [id: PostId]: Post;
  [id: UserId]: User;
} = {};
import { it } from "vitest";
import { Brand } from "../helpers/Brand";
import { Equal, Expect } from "../helpers/type-utils";

type PostId = Brand<string, "PostId">;
type UserId = Brand<string, "UserId">;

interface User {
  id: UserId;
  name: string;
}

interface Post {
  id: PostId;
  title: string;
}

const db: {
  [id: PostId]: Post;
  [id: UserId]: User;
} = {};

it("Should let you add users and posts to the db by their id", () => {
  const postId = "post_1" as PostId;
  const userId = "user_1" as UserId;

  db[postId] = {
    id: postId,
    title: "Hello world",
  };

  db[userId] = {
    id: userId,
    name: "Miles",
  };

  const post = db[postId];
  const user = db[userId];

  type tests = [
    Expect<Equal<typeof post, Post>>,
    Expect<Equal<typeof user, User>>,
  ];
});

it("Should fail if you try to add a user under a post id", () => {
  const postId = "post_1" as PostId;
  const userId = "user_1" as UserId;

  const user: User = {
    id: userId,
    name: "Miles",
  };

  // @ts-expect-error
  db[postId] = user;
});

 

posted @   Zhentiw  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2019-02-06 [TypeScript] Type Definitions and Modules
2019-02-06 [Tools] Add a Dynamic Tweet Button to a Webpage
2019-02-06 [Algorithm] Find Nth smallest value from Array
2018-02-06 [Javascript] Delegate JavaScript (ES6) generator iteration control
2017-02-06 [React] Use React.cloneElement to Extend Functionality of Children Components
2017-02-06 [React] Use React ref to Get a Reference to Specific Components
2017-02-06 [React] Normalize Events with Reacts Synthetic Event System
点击右上角即可分享
微信分享提示