tmkook
0.51D
V2EX  ›  TypeScript

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

By tmkook at 2025 年 6 月 20 日 · 2551 次点击
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 条附言  ·  2025 年 6 月 20 日
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 条附言  ·  2025 年 6 月 21 日

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

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

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

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

不知道是不是你要的
tmkook
   4
tmkook  
OP
PRO
   2025 年 6 月 21 日
@bjzhou1990 不行,似乎实现不了,估计递归太复杂无法推断返回的类型
nebnyp410404
   5
nebnyp410404  
   2025 年 6 月 21 日
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')
© 2026 V2EX · 405ms · 3.9.8.5