typescript - KeysOfType 和确切的属性类型
问题描述
我正在使用来自https://stackoverflow.com/a/49752227的 KeysOfType :
type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp? P : never }[keyof T];
有了这些接口
interface SomeInterface {
a: number;
b: string;
}
interface AnotherInterface {
a: number;
b: string;
c: number;
d: string;
}
interface DataInterface {
someProp: SomeInterface;
anotherProp: AnotherInterface;
...
}
如果我像下面显示的那样使用它,我会收到错误
类型“SomeInterface”不可分配给类型“SomeInterface & AnotherInterface”。
“SomeInterface”类型缺少“AnotherInterface”类型的以下属性:c、d
const setProperty = (numberValue: number, stringValue: string, propName: KeysOfType<DataInterface, SomeInterface>) => {
const obj: SomeInterface = {
a: numberValue,
b: stringValue
};
data[propName] = obj; // data is DataInterface
}
如何获取完全具有 SomeInterface 类型的 DataInterface 的属性键?
解决方案
正在发生的事情是,在分配的那一刻,propName
是 type "someProp" | "anotherProp"
。
Typescript 做了一件简单的事情:
- 我可以放在
obj
里面data.someProp
吗?是的 - 我可以放在
obj
里面data.anotherProp
吗?否 -> 错误
为了向您证明这是真的,请查看以下游乐场:游乐场
具有以下代码有效:
if (propName === 'someProp') {
data[propName] = obj;
}
推荐阅读
- kubernetes - Pod 因内存或 OOMKilled 而被驱逐
- git - 如何将新更改转发到 1 个月前的功能分支
- laravel - 如何在 Laravel 中显示多个有价值的列
- powershell - 新行和/或回车未转换
- laravel - Laravel 查询排序与 2 个表
- sql - CASE 表达式在 SQL Server 中有效,但在 Visual Studio Reporting Services 中无效
- unity3d - Agora Unity - PushAudioFrame
- excel - 使用集合时过程调用或参数无效
- jmeter - 为什么 JMeter 服务测试不稳定?
- ldap - 需要有关使用 Ldap 高可用性杂项检查脚本的 keepalived 的帮助