V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
tmkook
V2EX  ›  TypeScript

typescript 如何返回一个动态对象类型

  •  
  •   tmkook · 26 天前 · 1051 次点击
    class a extends schema {
        fun1 () => 1
    }
    class b extends schema{
        fun2 () => 2
    }
    
    const objs = {
        a:new a
        b:new b
    }
    
    function find(key) : any{
        return objs[key]
    }
    

    这个 objs 很多个 obj 他们都继承自同一个父类,有什么办法在调用 find 返回的对象能保持代码提示吗?

    let obj = find('a')
    obj.fun1 //代码提示
    
    
    第 1 条附言  ·  26 天前
    class Schema{
       protected json: Record<string, any> = {}
    
      attr(key:string,value:any){
         this.json[key] = value
      }
    
       find(id:string){
        return finder(this.json, id)
      }
    }
    
    
    function finder(obj: Record<string, any>, id: string) {
     // 递归查找 id 对应的 obj 
     // obj 都是继承自 Schema 的
     return obj
    }
    
    
    let a = new Schema
    a.find('b')
    

    json 里的内容是动态,似乎无法实现,试了好几个AI改出来的都不对。

    第 2 条附言  ·  25 天前

    https://github.com/tmkook/adomis/blob/main/src/components/schema.ts

    抱歉可能是我的案例不够严谨,试了各位的办法似乎都不行,附上源码,是这个文件中的 find 方法。 这种复杂的动态类型是不是没法推断?

    5 条回复    2025-06-21 17:50:40 +08:00
    RomeoHong
        1
    RomeoHong  
       26 天前   ❤️ 2
    type Objs = typeof objs;
    function find<K extends keyof Objs>(key: K): Objs[K] {
    return objs[key]
    }
    tmkook
        2
    tmkook  
    OP
       26 天前
    @RomeoHong 感谢回复,我的例子好像不太对。还是没有解决,我补充一下。
    bjzhou1990
        3
    bjzhou1990  
       26 天前   ❤️ 1
    function find<T extends Schema>(key: string): T {
    return objs[key]
    }

    const c = find('a')
    c.attr('a', 'b')

    不知道是不是你要的
    tmkook
        4
    tmkook  
    OP
       25 天前
    @bjzhou1990 不行,似乎实现不了,估计递归太复杂无法推断返回的类型
    nebnyp410404
        5
    nebnyp410404  
       25 天前
    class schema {
    func: Function
    }

    class a extends schema {
    fun1: () => 1
    }
    class b extends schema{
    fun2: () => 2
    }

    const objs = {
    a:new a,
    b:new b
    }

    type Key = keyof typeof objs;

    function find<T extends Key>(key: T): typeof objs[T] {
    return objs[key];
    }

    const cc = find('a')
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3119 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 11:30 · PVG 19:30 · LAX 04:30 · JFK 07:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.