简体   繁体   English

Typescript 打字属性吸气剂创建者

[英]Typescript typing property getter creator

My issue is similar to the one described here and here (and probably other places too).我的问题类似于此处此处(可能还有其他地方)描述的问题。 I feel like it's a simple Lookup Type issue ( documented here ).我觉得这是一个简单的查找类型问题( 在此处记录)。 But my use case is slightly different and I cannot get it to work.但我的用例略有不同,我无法让它工作。

I have a function that takes an object of Type and returns a "getter" function for this object.我有一个 function ,它采用 object Type并为此 ZA8ZFDE6331BD4B62661 返回一个“getter” function Here's a simple playground. 这是一个简单的游乐场。

type User = {
    name: string,
    age: number,
};

const makeGetter = <Type, Key extends keyof Type>(obj: Type) => (key: Key) => obj[key];

const user: User = {
    age: 55,
    name: 'Brian',
};

const getter = makeGetter(user);
const u = getter('age');

However, the selected property is always a union of all possible property types.但是,选定的属性始终是所有可能的属性类型的联合。

What am I missing?我错过了什么?

The problem is that your generic will be created on creation of the makeGetter function.问题是您的泛型将在创建 makeGetter function 时创建。 At this time Key isn't resolved to a specific key yet.此时Key尚未解析为特定的键。 Move the generic to the curried function.将泛型移动到咖喱 function。

const makeGetter = <Type extends Object>(obj: Type) => <K extends keyof Type>(key: K) => obj[key]

Playground 操场

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

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