简体   繁体   English

Typescript 类型断言,可以是数组或普通类型

[英]Typescript type assertion for type that can be an array or plain

I'm currently working with the @octokit/rest library in typescript.我目前正在使用 typescript 中的@octokit/rest库。 Currently stuck on how to narrow a certain type to what I want.目前坚持如何将某种类型缩小到我想要的范围内。 Here's the response object from the endpoint I'm calling:这是来自我正在调用的端点的响应 object:

  type ReposGetContentsResponse =
    | {
        _links: ReposGetContentsResponseLinks;
        content?: string;
        download_url: string | null;
        encoding?: string;
        git_url: string;
        html_url: string;
        name: string;
        path: string;
        sha: string;
        size: number;
        type: string;
        url: string;
        target?: string;
        submodule_git_url?: string;
      }
    | Array<ReposGetContentsResponseItem>

I'm having trouble with checking if the returned response object is the object or array type.我无法检查返回的响应 object 是 object 还是数组类型。 In my case, I only want to use the object, as returning the array indicates that a user passed in a directory rather than a file path .就我而言,我只想使用 object,因为返回数组表示用户传入的是目录而不是文件path

Here's my code so far:到目前为止,这是我的代码:

  // Returns contents of a file, if ref is not specified, it will use the default branch.
  async getFileContents(path: string, ref?: string) {
    let fileInfo: octokit.Response<octokit.ReposGetContentsResponse>;
    const owner = this.owner;
    const repo = this.repo;
    if (ref) {
      fileInfo = await this._client.repos.getContents({owner, repo, path, ref});
    } else {
      fileInfo = await this._client.repos.getContents({owner, repo, path});
    }
    // Only want a single file response, if we get an array, something went wrong.
    // This is not working, how do I ensure that this *isn't* the type octokit.ReposGetContentsResponse[] ?
    if (!fileInfo.data instanceof Object) {
      if (fileInfo.data.type !== 'file') {
        return null;
      }
      const buffer = Buffer.from(fileInfo.data.content, 'base64');
      return buffer.toString('utf-8');
    }
    return null;
  }

You can use .Array.isArray(fileInfo.data) && typeof fileInfo.data === 'object' to check if a variable is array or not and it is an object.您可以使用.Array.isArray(fileInfo.data) && typeof fileInfo.data === 'object'来检查变量是否为数组并且它是 object。

This way you can only use objects and it will filter array.这样你只能使用对象,它会过滤数组。

Anything wrong with a simple check on length?简单检查长度有什么问题吗?

var arr = [];
var obj = {};

typeof arr.length !== 'undefined' // true
typeof obj.length !== 'undefined' // false

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

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