【问题标题】:Generic Typescript Method to return any of the Object key types or Object type itself based on input基于输入返回任何 Object 键类型或 Object 类型本身的通用 Typescript 方法
【发布时间】:2020-12-18 18:22:45
【问题描述】:

我想定义一个 typescript 方法,该方法可以返回 Object 类型或 Object 的任何属性。 例如

Person {
   Education,
   Bio
}

通用函数可以根据所提供的输入返回 PersonEducationBio,比如 Enum 类型。

let person = testFunction(TypePerson); // complete person 

let personEducation = testFunction(TypeEducation); // person's education

人物类型只是举例,但这里可以是任何东西,属性不会提前知道。

例如,而不是 Person 让我们说 got

Vehicle {
  PropertyType1,
  SomeProperties
}

【问题讨论】:

  • 您能分享一下您的期望吗?

标签: typescript generics typescript-generics functional-interface


【解决方案1】:

我想你是在问函数重载。

interface Person {
  Education: string;
  Age: number;
}

interface Vehicle {
  doors: number;
  color: 'pink' | 'red';
}

enum Data {
  person = 'person',
  car = 'car'
}

function getData(data: Data.car): Vehicle
function getData(data: Data.person): Person
function getData(data: Data) {
  return 'your implementation' as any
}

const result1 = getData(Data.person) //Person
const result2 = getData(Data.car) //Vehicle

Here你可以找到更多信息

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 2019-10-29
    • 2018-10-19
    • 2012-04-26
    • 2020-09-04
    • 2019-06-07
    • 2019-12-19
    • 1970-01-01
    • 2018-06-20
    相关资源
    最近更新 更多