Typescript 获取HOF的typeguard防护类型

Typescript 获取HOF的typeguard防护类型,typescript,Typescript,我有以下简单的HOF function myHOF(input: any, typeguard: (thing: any) => boolean) { if (typeguard(input)) { return input; } } 具有typeguard功能 function myTypeguard(input: any): input is Array<any> { return Array.isArray(input); } 函数myTypegu

我有以下简单的HOF

function myHOF(input: any, typeguard: (thing: any) => boolean) {
  if (typeguard(input)) {
    return input;
  }
}
具有typeguard功能

function myTypeguard(input: any): input is Array<any> {
  return Array.isArray(input);
}
函数myTypeguard(输入:any):输入为数组{
返回数组.isArray(输入);
}
用作

const val = [1,2];
const thing = myHOF(val, myTypeguard);  // <- should be Array<any> | undefined
const val=[1,2];

const thing=myHOF(val,myTypeguard);// 当然,您可以在高阶函数中使用类型保护签名。事实上,使用此选项可以返回比筛选的数组更窄的数组:

接口数组{
滤器(
callbackfn:(值:T,索引:number,数组:T[])=>值是S,
thisArg?:有吗
):S[];

无论如何,以你为例:

function myHOF<T>(input: any, typeguard: (thing: any) => thing is T) : T | undefined {
  if (typeguard(input)) {
    return input;
  }
  return;
}

编辑:我不能100%确定您使用
PlanNode
的其他案例,但可能是:

export function* depthFirstRetrieval<T extends PlanNode, L extends PlanNode>(
  jxml: T,
  stopConditional: (obj: PlanNode) => obj is L,
): IterableIterator<L>
{
  if (stopConditional(jxml)) {
    yield jxml;
  } else {
    for (const key of Object.keys(jxml) as Array<keyof typeof jxml>) {
      const property = jxml[key];
      if (Array.isArray(property)) {
        for (const childNode of property) {
          yield *depthFirstRetrieval(childNode, stopConditional);
        }
      }
    }
  }
}
导出功能*depthFirstRetrieval(
jxml:T,
stopConditional:(对象:平面节点)=>对象为L,
):IterableIterator
{
if(stopConditional(jxml)){
产生jxml;
}否则{
for(Object.keys(jxml)的常量键作为数组){
const property=jxml[key];
if(Array.isArray(属性)){
for(属性的const childNode){
收益率*depthFirstRetrieval(childNode,stopConditional);
}
}
}
}
}

希望有帮助;祝你好运!

太好了!这正是我需要的。
function myTypeguard(input: any): input is Array<any> {
  return Array.isArray(input);
}

const val = [1,2];
const thing = myHOF(val, myTypeguard);  // thing is any[] | undefined
export function* depthFirstRetrieval<T extends PlanNode, L extends PlanNode>(
  jxml: T,
  stopConditional: (obj: PlanNode) => obj is L,
): IterableIterator<L>
{
  if (stopConditional(jxml)) {
    yield jxml;
  } else {
    for (const key of Object.keys(jxml) as Array<keyof typeof jxml>) {
      const property = jxml[key];
      if (Array.isArray(property)) {
        for (const childNode of property) {
          yield *depthFirstRetrieval(childNode, stopConditional);
        }
      }
    }
  }
}