Typescript - 创建可区分联合的子集作为可区分联合

问题描述 投票:0回答:1

有没有办法通过从另一个判别联合中选取一些字段来创建子集判别联合?

例如:

type Listing = {
  type: 'rent';
  title: string;
  userId: string;

  dailyPrice: number;
  monthlyPrice: number;
  
} | {
  type: 'sell',
  title: string;
  userId: string;
  
  sellPrice: number;
}

进入

type ListingBrief {
  type: 'rent';
  dailyPrice: number;
  monthlyPrice: number;
} | {
  type: 'sell';
  sellPrice: number;
}

所以我想要的是类似

Pick<Listing, 'type' | 'dailyPrice' | 'monthlyPrice' | 'salePrice'>
的东西。但 Typescript 似乎不允许选取仅存在于一种类型的字段,即
dailyPrice
monthlyPrice
salePrice
。可以选择像
title
userId
这样的字段,因为它们存在于所有类型中。

typescript discriminated-union typescript-utility
1个回答
0
投票

不确定您要什么,但是您可以将原始联合分成两种不同的类型:

type ListingRent = {
  type: 'rent';
  title: string;
  userId: string;

  dailyPrice: number;
  monthlyPrice: number;
}

type ListingSell = {
  type: 'sell',
  title: string;
  userId: string;
  
  sellPrice: number;
}

type Listing = ListingRent | ListingSell;

此时,结果就很简单了:

type ListingRentBrief = Pick<ListingRent, 'type' | 'dailyPrice' | 'monthlyPrice'>

type ListingSellBrief = Pick<ListingSell, 'type' | 'salePrice'>

type ListingBrief = ListingRentBrief | ListingSellBrief;

这是你所期待的吗?如果没有的话我就删掉它。

© www.soinside.com 2019 - 2024. All rights reserved.