typescript泛型约束如下报错,跪求正确写法?

interface Table<T> {
    [index: string]: T;
}

interface IPeople {
    sex:string;
    age:number;
    name:string;
}

class People implements IPeople {
    public sex:string = "man";
    public age:number = 30;
    public name:string = "老王"
}

class Chinese extends People {
    public country:string = "ch"
}

class A {
    public p:Table<IPeople> = {}
    public fun<T extends People>(param:T):T{
        return this.p[param]
    }
}

提示报错

Type 'T' cannot be used to index type 'IPeople'.
回复
阅读 355
1 个回答

不知道你这个 fun 是干什么用的

因为你这个 pTable 所以索引用 string 就行了

public fun(param: string): People {
    return this.p[param]
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
Microsoft
子站问答
访问
宣传栏