首页 > 解决方案 > 从字符串名称中获取接口属性的类型

问题描述

我有一个类RObject,它需要一个预计是接口类型的泛型。该接口包含此对象的虚拟属性的定义。我想制作考虑给定模式接口的正确类型getProp和方法。setProp

例如,采用以下测试实现:

interface FooSchema {
  strProp: string;
  numProp: number;
}

const newObj = new RObject<FooSchema>();

newOBj.setProp('strProp', 'some string'); // only allow setting to string since `strProp` is a string in the `FooSchema`.
newOBj.setProp('numProp', 1); // only allow setting to number since `numProp` is a number in the `FooSchema`.
newObj.setProp('numProp', 'bad value'); // this should not be allowed since `numProp` is a number on `FooSchema`.

const strValue: string = newObj.getProp('strProp'); // this is allowed.
const numValue: number = newObj.getProp('strProp'); // this should not be allowed.

到目前为止我所拥有的:

class RObject<S> {
  public getProp<ValueType extends S[keyof S]>(key: Extract<keyof S, string>): ValueType {
    // ...
  }

  public setProp<ValueType extends S[keyof S]>(key: Extract<keyof S, string>, value: ValueType) {
    // ...
  }
}

到目前为止,我可以获得第一个key参数以正确强制它必须是模式键的字符串名称。但我不知道如何获取正在获取或设置的属性的类型。的第二个参数setProp是允许任何类型,只要它出现在架构中的某处。并且getProp也允许模式中的任何类型的返回类型。如何将值类型限制为正在操作的确切值的类型?

所以基本上我需要一种从字符串 name 中获取接口属性类型的方法key。喜欢做的能力typeof S[key]

标签: typescript

解决方案


推荐阅读