typescript - 从字符串名称中获取接口属性的类型
问题描述
我有一个类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]
。
解决方案
推荐阅读
- java - 违反主键约束:Hibenate 保存方法不更新但尝试插入具有相同主键的新行
- jquery - 无法更改提交按钮的名称
- javascript - 如何根据单个数组元素中的重复日期过滤数据
- php - 如何从 Laravel 6.2 中 PasswordResetNotification 中的 toMail 方法获取邮件
- python - 如何打乱这个 3D numpy 数组的前两个维度?
- c# - 物体不会连续移动
- azure - 如何调试从不触发的 Microsoft Graph API 订阅?
- image - 在天蓝色的规模集后面创建虚拟机的图像
- mysql - SQL 获取带有类别和 post_tag 的 WordPress 帖子
- ios - Instagram 分享不再有效?