Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript KeysOfType和属性的确切类型_Typescript_Typescript Typings - Fatal编程技术网

Typescript 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

我使用的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 {
  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
的可复制示例。我只是不知道你从哪里得到的
数据
变量