[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;
});
分类:
TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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