从对象联合中省略一个对象
我使用的库将类型定义为:
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' }>
回答
您可以Exclude为此使用(但请继续阅读):
type SuccessLogInResult = Exclude<LogInResult, {type: 'cancel'}>;
它通过从第一个(联合)类型中排除第二个类型来创建一个类型。
游乐场链接
看起来您也可以使用Extract,这可能更直观:
type SuccessLogInResult = Extract<LogInResult, {type: 'success'}>;
我本以为我必须type在那里的第二种类型参数中包含更多,但显然不是,因为它似乎有效:
游乐场链接