根据返回类型限制“类型"的键 [英] Restrict keyof 'Type' according to return type

查看:128
本文介绍了根据返回类型限制“类型"的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将对象的键限制为仅返回某种类型的键?

How can I restrict the keys of an object to only those that return a certain type?

在下面的示例中,我想确保属性的类型是一个函数,以便我可以执行obj[key]().

In the example below I want to ensure that the type of the property is a function, so that I can execute obj[key]().

interface IObj{
  p1:string,
  p2:number,
  p3:()=>void
}

const obj:IObj = {
  p1:'str',
  p2:5,
  p3:()=>void 0
}

function fun<TKey extends keyof IObj>(key: IObj[TKey] extends ()=>void? TKey:never){
  const p = obj[key]
  p(); // This expression is not callable.
       // Not all constituents of type 'string | number | (() => void)' are callable.
       // Type 'string' has no call signatures.(2349)
}

操场

推荐答案

您可以将类型映射到属性名/从不,然后再对其进行索引,而您已经拥有了一半:

You can map the type to property name/never and then index into it, you have half of that already:

type FunctionKeys = {
    [K in keyof IObj]: IObj[K] extends () => void ? K : never
}[keyof IObj]; // <-

function fun(key: FunctionKeys) {
    const p = obj[key];
    p();
}

索引将对所有类型的属性执行并集,而A | never只是A.

The indexing will perform a union over all the types of the properties and A | never is just A.

(提取了类型,因为它太长了.也许有一个更优雅的方法.)

(Extracted the type because it's so long. Maybe there is a more elegant method.)

这篇关于根据返回类型限制“类型"的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆