首页 > 解决方案 > 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 的属性键?

标签: typescripttypescript-typings

解决方案


正在发生的事情是,在分配的那一刻,propName是 type "someProp" | "anotherProp"

Typescript 做了一件简单的事情:

  • 我可以放在obj里面data.someProp吗?是的
  • 我可以放在obj里面data.anotherProp吗?否 -> 错误

为了向您证明这是真的,请查看以下游乐场:游乐场

具有以下代码有效:

  if (propName === 'someProp') {
    data[propName] = obj;
  }

推荐阅读