如何在 Typescript 中正确缩小类型?

问题描述

我正在使用 Octokit,这是一个 GitHub 客户端。我正在尝试读取目录的内容octokit.repos.getContent 的返回类型是一个具有许多可能值的类型联合。

我正在尝试将 getContent 的返回值缩小到仅这些选项之一,它看起来像这样:

"content-directory": {
    type: string;
    size: number;
    name: string;
    path: string;
    content?: string;
    sha: string;
    url: string;
    git_url: string | null;
    html_url: string | null;
    download_url: string | null;
    _links: {
        git: string | null;
        html: string | null;
        self: string;
    };
}[]

我用它创建了一个 type

type DirectoryItems = components["schemas"]["content-directory"];

现在我试图在类型保护中使用它:

const { data } = await octokit.repos.getContent({
    // ...
});

if(data instanceof DirectoryItems) {

}

但它说

'DirectoryItems' 仅指一种类型,但在此处用作值。

如何缩小 data 的类型以确保它确实是“内容目录”项的数组?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)