[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;
});