首页 > 解决方案 > 从对象的联合中省略一个对象

问题描述

我使用的库将类型定义为:

export declare type LogInResult = {
    type: 'cancel';
} | {
    type: 'success';
    accessToken: string | null;
    idToken: string | null;
    refreshToken: string | null;
    user: GoogleUser;
};

SuccessLoginResult我想通过省略对象来创建类型{ type: 'cancel' },这可能吗?

我试过的一些伪代码不起作用:

type SuccessLoginResult = Omit<LogInResult, { type: 'cancel' }>

标签: typescript

解决方案


您可以使用Exclude(但请继续阅读)

type SuccessLogInResult = Exclude<LogInResult, {type: 'cancel'}>;

它通过从第一个(联合)类型中排除第二个类型来创建一个类型。

游乐场链接

看起来你也可以使用Extract,这可能更直观:

type SuccessLogInResult = Extract<LogInResult, {type: 'success'}>;

我原以为我必须type在第二类参数中包含更多内容,但显然不是,因为它似乎有效:

游乐场链接


推荐阅读