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 //代码提示
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改出来的都不对。
https://github.com/tmkook/adomis/blob/main/src/components/schema.ts
抱歉可能是我的案例不够严谨,试了各位的办法似乎都不行,附上源码,是这个文件中的 find 方法。 这种复杂的动态类型是不是没法推断?
1
RomeoHong 26 天前 ![]() type Objs = typeof objs;
function find<K extends keyof Objs>(key: K): Objs[K] { return objs[key] } |
![]() |
3
bjzhou1990 26 天前 ![]() function find<T extends Schema>(key: string): T {
return objs[key] } const c = find('a') c.attr('a', 'b') 不知道是不是你要的 |
![]() |
4
tmkook OP @bjzhou1990 不行,似乎实现不了,估计递归太复杂无法推断返回的类型
|
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') |