[英]typescript return property data of interface, return type definition
I have an function where I want to query data from an data object structured by an interface.我有一个 function,我想从由接口结构化的数据 object 中查询数据。 This function should resolve the property data form the data object.
这个 function 应该从数据 object 解析属性数据。 This is working if I have any as return type, however there should be a better approach, where the return type will be the type of the property.
如果我有任何作为返回类型,这是可行的,但是应该有更好的方法,其中返回类型将是属性的类型。
Here is my approach: Coding这是我的方法:编码
There I only get back an union type of all properties of the interface, however I should get back the type of the property that I want to return.那里我只取回接口的所有属性的联合类型,但是我应该取回我想要返回的属性的类型。
You should make getData
generic and then reuse the generic type for both argument and return value:您应该使
getData
通用,然后为参数和返回值重用通用类型:
interface Rofl {
name:string,
id:number,
}
const data: Rofl = {
name:"lol",
id:1,
};
function getData<T extends keyof Rofl>(property: T): Rofl[T] {
return data[property];
}
const lol:string = getData("name");
https://www.typescriptlang.org/play?ssl=16&ssc=29&pln=16&pc=33#code/JYOwLgpgTgZghgYwgAgEoHsYBtkG8CwAUMsiHALYQBcAzmFKAOYA0RJwAJlSAK7kBG0VoQC+RIgnQg6yDnDBwqaTDgC8eNqQrUARFnRYdw9lwCMwkQG5xhGDxAIwwKckYQwAEXlwAPABVkCAAPSBAOGmQAawgAT0xlbAA+AAoAByh0VOgwGKU-AEolDGwAbT8AXQ1iZCh3HigQWW8S9MzsmPLrURsJKRl9LFp6JmR1N09vZJ0ySh18rt7pAwgAOn1GZIH5oA https://www.typescriptlang.org/play?ssl=16&ssc=29&pln=16&pc=33#code/JYOwLgpgTgZghgYwgAgEoHsYBtkG8CwAUMsiHALYQBcAzmFKAOYA0RJwAJlSAK7kBG0VoQC+RIgnQg6yDnDBwqaTDgC8eNqQrUARFnRYdw9lwCMwkQG5xhGDxAIwwKckYQwAEXlwAPABVkCAAPSBAOGmQAawgAT0xlbAA+AAoAByh0VOgwGKU-AEolDGwAbT8AXQ1iZCh3HigQWW8S9MzsmPLrURsJKRl9LFp6JmR1N09vZJ0ySh18rt7pAwgAOn1GZIH5oA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.