从其字符串名称获取接口属性的类型

时间:2019-12-29 22:07:44

标签: typescript

我有一个类RObject,该类需要一个通用类型的接口类型。该接口包含此对象的虚拟属性的定义。我想制作考虑到给定架构接口的正确类型的getPropsetProp方法。

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

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也允许模式中任何类型的返回类型。如何将值类型限制为要操作的确切值的类型?

因此,基本上,我需要一种方法来从字符串名称key中获取接口属性的类型。喜欢做typeof S[key]的能力。

0 个答案:

没有答案