TS 定义动态对象

857 阅读1分钟

前言

刚写ts代码, 给我的感觉是,空对象不好声明 (这里指动态添加属性) 。

我遇到如下:

 type fnType = (param: string)=> void
   type fn =  (type: string, fn:fnType) => void
   interface ClientLists{
     [type: string]: fnType[]
   }
   const Event = {
     clientLists: {

     } as ClientLists,
     
     listen: function (type: string , fn:fnType) :void{
       const keys = Object.keys(this.clientLists)
       const flag =  keys.find((item)=>item === type) //clientLists 是否已经注册过type
       if(!flag){
        this.clientLists[type] = []
       }
       
     },
     trigger: function () :void {
       
     },
     remove: function () :void {
       
     }

   }

分析:

  1. 问题: ClientLists 对象是个动态的, 我不知道他里面会放那些属性

    解决: 用可索引的类型

  2. 问题: ClientLists 字面量的声明方式

    解决: 用断言

不喜勿喷, 各位大佬如果有更好的办法 ,欢迎留言交流。