Typescript KeysOfType和属性的确切类型
我使用的KeysOfType来自:Typescript KeysOfType和属性的确切类型,typescript,typescript-typings,Typescript,Typescript Typings,我使用的KeysOfType来自: type KeysOfType={[p in keyof T]:T[p]扩展了TProp?p:never}[keyof T] 使用这些接口 interface SomeInterface { a: number; b: string; } interface AnotherInterface { a: number; b: string; c: number; d: string; } interface DataInterface
type KeysOfType={[p in keyof T]:T[p]扩展了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
}
const setProperty=(numberValue:number,stringValue:string,propName:KeysOfType)=>{
常量对象:SomeInterface={
a:数值,
b:stringValue
};
data[propName]=obj;//数据是数据接口
}
如何获取数据接口的属性键,而这些属性键的类型正好是SomeInterface?发生的事情是,在赋值时,propName
的类型是“someProp”|“anotherProp”
Typescript做了一件简单的事情:
- 我是否可以将
obj
放在数据的内部。someProp
?对
- 我可以把
obj
放在数据的内部吗。另一个属性
?否->错误
为了向您证明这是真的,请查看以下游乐场:
具有以下代码可以工作:
if (propName === 'someProp') {
data[propName] = obj;
}
请分享setProperty
的可复制示例。我只是不知道你从哪里得到的数据
变量