首页 > 其他分享 >[Typescript] Indexing an Object with Branded Types

[Typescript] Indexing an Object with Branded Types

时间:2023-02-06 03:55:05浏览次数:37  
标签:Typescript const userId Object db postId UserId Branded id

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,const,userId,Object,db,postId,UserId,Branded,id
From: https://www.cnblogs.com/Answer1215/p/17094312.html

相关文章

  • Objective-C语法学习 第一天
    关于引用计数的内存管理1.内存管理必要性ARC是MacOSX10.7和iOS5引入的新特性,也是苹果公司推荐是用的内存管理方法。启用ARC后,编译器会在适当的地方自动加入retain,releas......
  • ObjectPool 对象池
    对象池ObjectPool位于 Microsoft.Extensions.ObjectPool命名空间主要有三个对象:ObjectPool:对象池,用于存放对象ObjectPoolProvider:对象池提供者,用于创建Object......
  • python中class,type和object的关系
    #记录一下,截取的是B站python教程_的视频的图片就理解一切皆对象,都是type的实例,都继承的objectclass类实例化对象,class本身也是个对象type(1)的为<class'int'>意......
  • Java实现JSONObject对象与Json字符串互相转换
    Java实现JSONObject对象与Json字符串互相转换JSONObject转JSON字符串Java代码: JSONObjectjsonObject=newJSONObject();jsonObject.put("name","wjw")......
  • 使用pdfobject预览pdf
    之前写过一篇预览pdf的,​​Vue使用vue-pdf实现PDF文件预览​​ ,大家按需所用一般项目中在上传文件之前可能会有先预览一下,看是否符合要求,符合再上传,这里先说了pdf文件,使用......
  • SVG foreignObject All In One
    SVGforeignObjectAllInOneSVGforeignObjectThe<foreignObject>SVGelementincludeselementsfromadifferentXMLnamespace.Inthecontextofabrowser......
  • [Typescript] Defining exclusive properties with TypeScript
    typeA={other:'string',url:'string'}typeB={other:'string',ids:'string'}typeExclusive<TextendsRecord<PropertyKey,unknown>,UextendsReco......
  • ObjectPool
    usingSystem;usingSystem.Collections.Concurrent;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceObjectPoolExample{publicclassObjec......
  • Vue3 Vite 打包后页面报错 Function has non-object prototype 'undefined' in instan
    问题原本可以正常打包部署运行,前两天加了些新功能,再打包就遇到这个问题,其意为:函数在instanceofcheck中具有非对象原型“undefined”TypeError:Functionhasnon-object......
  • flutter —— RenderObject 的布局原理
    RenderObject的布局原理①relayoutBoundary重布局边界。该参数用于表示子节点布局变化是否影响父节点,如果为true,当子节点布局发生变化时父节点都会标记为需要重新布局,......