简体   繁体   English

根据返回类型限制'Type'的key

[英]Restrict keyof 'Type' according to return type

How can I restrict the keys of an object to only those that return a certain type?如何将对象的键限制为仅返回特定类型的键?

In the example below I want to ensure that the type of the property is a function, so that I can execute obj[key]() .在下面的示例中,我想确保属性的类型是函数,以便我可以执行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)
}

playground 操场

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();
}

The indexing will perform a union over all the types of the properties and A | never索引将对所有类型的属性和A | never执行联合A | never A | never is just A . A | never只是A

(Extracted the type because it's so long. Maybe there is a more elegant method.) (提取类型是因为它太长了。也许有更优雅的方法。)

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

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