typescript 如何在类型语法中使用值

eivgtgni  于 2023-04-13  发布在  TypeScript
关注(0)|答案(1)|浏览(108)

我想我的方法的返回类型是我的类的属性之一(动态),我怎么能做到这一点?
就像这样:

interface IObject {
  [key: string]: any
}

class classX<T extends IObject> {
  public methodX(column: keyof T) {
    return (null as any) as T[`${column}`] // T['property']
  }
}
const varX = new classX<{ property: string }>()
varX.methodX('property') // expected type string

const varY = new classX<{ property: number }>()
varY.methodX('property') // expected type number
gjmwrych

gjmwrych1#

只需在方法中添加一个泛型约束,并使用它来约束参数和返回类型:

interface IObject {
  [key: string]: any
}

class classX<T extends IObject> {
  public methodX<K extends keyof T>(column: K): T[K] {
    return (null as any) as T[K];
  }
}

const varX = new classX<{ property: string }>();
varX.methodX('property');

const varY = new classX<{ property: number }>();
varY.methodX('property');

Playground链接

相关问题