繁体   English   中英

使用 typescript 中的通用类型从 object 返回具有正确类型的属性

[英]Return property from object with correct type using generic typing in typescript

我曾多次尝试实现从 object 中提取属性的通用函数。 Typescript 下面的代码返回字符串 | 数字,虽然我想让它知道它会专门返回一个字符串或一个数字。 在普通的 JS 中,我知道下面的代码会返回一个字符串并做出相应的反应,所以我希望可以摆脱 Typescript 中如何解决这个问题的任何线索。

interface Person {
  name: string;
  age: number;
}

const getPropertyByKey = (
  person: Person
) => (
  key: keyof Person
) => person[key];

const person = {
  name: 'Thomas',
  age: 32
};

const property = (person)('name'); // Should realise it is a string

使部分 function 泛型,它将能够根据key的特定字符串值推断返回值的类型。

interface Person {
  name: string;
  age: number;
}

const getPropertyByKey = (
  person: Person
) => <K extends keyof Person>(
  key: K
) => person[key];

const person = {
  name: 'Thomas',
  age: 32
};

const property = getPropertyByKey(person)('name');

游乐场链接

我想你必须告诉 TS 你想要什么。 它有点冗长:

const getPropertyByKey = (person: Person) => (key:any) => 
  "number" === typeof key ? person["age"] : person["name"];

这应该适用于您的示例

function prop<T, V extends keyof T>(val: T, key: V): T[V] {
  return val[key];
}


const prop1 = prop({ id: 1, name: 'Pete' }, 'id'); // number
const prop2 = prop({ id: 1, name: 'Pete' }, 'name'); // string

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM