简体   繁体   English

返回属性名称字符串文字值的 TypeScript 函数?

[英]TypeScript function that returns value for string literal of property name?

Consider this TypeScript function that returns the value of an objects property:考虑这个返回对象属性值的 TypeScript 函数:

export function getProperty<T>(object: T, key: string): any {
    return (object as any)[key]
}

It is not very nice to use, since it always returns an any :它不是很好用,因为它总是返回一个any

interface Animal {
    name: string,
    hungry: boolean,
}

const myHippo: Animal = {
    name: "Hippo",
    hungry: true,
}

const name = getProperty(myHippo, "name") // Returns any, but I want a string.
const size = getProperty(myHippo, "size") // Returns any, but I want a compiler error.

I would like it to return a value with the correct type, eg string for "name" , and cause a compiler error if the string literal provided in key is not a property of object .我想这是正确类型返回一个值,例如string"name" ,并导致编译错误,如果提供的字符串字面key是没有的属性object (I do not need to support non literal strings, those can be compiler errors too.) (我不需要支持非文字字符串,那些也可能是编译器错误。)

Is this even possible with TypeScript?这甚至可以用 TypeScript 实现吗? I suspect not, but I am not sure.我怀疑不是,但我不确定。

Something that would be useful as a step in the right direction would be an utility type Keys<T> that represent the union of all string literals that are property names in T .作为朝着正确方向迈出的一步,有用的东西是实用程序类型Keys<T> ,它表示作为T中属性名称的所有字符串文字的联合。 But that doesn't seem to exist?但这似乎并不存在?

export function getProperty<T, K extends keyof T>(object: T, key: K): T[K] {
  return object[key];
}

This gives you the compiler failure you want and the return type matches the property type这为您提供了所需的编译器失败,并且返回类型与属性类型匹配

Playground Link 游乐场链接

暂无
暂无

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

相关问题 将属性定义为在 Typescript 中返回字符串的字符串或函数 - Define a property as string or function that returns a string in Typescript 打字稿字符串文字类型在函数重载中不起作用 - Typescript String Literal Types not working in function overloading TypeScript:提取字符串文字为 function 参数 - TypeScript: Extract string literal as function param Typescript 字符串字面量 通用类型 function - Typescript String Literal Type in generic function 有什么办法可以推断Typescript中define属性的字符串名称值? - Any way to infer the string name value of the defining property in Typescript? 如何将值传递给名称在 function 参数中传递到 TypeScript 中的属性? - How to pass value to property that name was passed in function parameter in TypeScript? 如何在 TypeScript 中的 function 的返回类型中使用参数的值作为属性名称? - How to use the value of a parameter as a property name in the return type for a function in TypeScript? 如何接受 function 中的字符串文字类型,然后接受 map 到 typescript 中的键值对? - How to accept string literal types in function and then map it to key-value pair in typescript? 是否可以在Typescript中使用预定义的字符串文字类型定义类属性 - Is it possible to define a class property with predefined string literal types in Typescript 打字稿将泛型约束为字符串文字类型以用于计算对象属性 - Typescript constrain generic to string literal type for use in computed object property
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM