Javascript 期望从服务器响应承诺中获得动态类型

Javascript 期望从服务器响应承诺中获得动态类型,javascript,node.js,typescript,Javascript,Node.js,Typescript,需要服务器响应的已解析承诺对象可以是any[]或{data:any[]}类型 到目前为止,我已经试过了: type ServerResponse = any[] | { data: any[] } 但是,当我尝试使用该类型时,会收到如下错误消息: Property 'data' does not exist on type 'ServerResponse'. Property 'data' does not exist on type 'any[]'. ts(2339) 或者 您需要实

需要服务器响应的已解析承诺对象可以是
any[]
{data:any[]}
类型

到目前为止,我已经试过了:

type ServerResponse = any[] | { data: any[] }
但是,当我尝试使用该类型时,会收到如下错误消息:

Property 'data' does not exist on type 'ServerResponse'. 
  Property 'data' does not exist on type 'any[]'. ts(2339)
或者


您需要实现一个类型保护。在下面的代码中,函数
isAnyArray
是一种类型保护

type ServerResponse = any[] | { data: any[] };

function isAnyArray(response: ServerResponse): response is any[] {
  return Array.isArray(response);
}

const someFunction(response: ServerResponse){
  if(isAnyArray(response)){
    response.forEach(x => {
      console.log(x);
    });
  } else {
    response.data.forEach(x => {
      console.log(x);
    });
  }
}

您需要实施类型保护。在下面的代码中,函数
isAnyArray
是一种类型保护

type ServerResponse = any[] | { data: any[] };

function isAnyArray(response: ServerResponse): response is any[] {
  return Array.isArray(response);
}

const someFunction(response: ServerResponse){
  if(isAnyArray(response)){
    response.forEach(x => {
      console.log(x);
    });
  } else {
    response.data.forEach(x => {
      console.log(x);
    });
  }
}

这并不完全构成如中所述的。你能提供一个独立的例子来说明你所说的“使用类型”是什么意思吗?答案可能很简单,比如
Array.isArray(x)?x:x.data
但是如果没有一个实际的例子,我不能确定。祝你好运这并不完全构成如中所述的。你能提供一个独立的例子来说明你所说的“使用类型”是什么意思吗?答案可能很简单,比如
Array.isArray(x)?x:x.data
但是如果没有一个实际的例子,我不能确定。祝你好运
//this function will provide the response in array format
 function ServerResponse(res) {
        if (!Array.isArray(res)) {
        res = res.data;
        }
        return res;
    }

// initialize two types of response    
    const a = [];
    const b = {data:[]};

  // both response will be in Array format
    console.log(ServerResponse(a));
    console.log(ServerResponse(b));