打字稿避免在 Intersection 中为可空值重复类型

时间:2021-01-19 10:07:16

标签: typescript

我用这种类型构建了一个对象数组

export type MyDto = { prods: {id:string} | null } & {name: string};

然后我过滤它以摆脱空类型,所以我得到了这种类型

export type MyFilteredDto = { prods: {id:string} } & {name: string};

有没有办法避免重复(不使用其他类型),例如使用实用程序类型?

2 个答案:

答案 0 :(得分:1)

您可以使用类型来指定类型的属性可为空:

type WithNullableProp<T, K extends keyof T> = T | {
  [k in K]: T[K] | null;
}

type MyFilteredDto = { prods: {id:string} } & {name: string};
type MyDto = WithNullableProp<MyFilteredDto, 'prods'>;

const test: MyDto = {
  prods: null,
  name: '1',
}

const test2: MyDto = {
  prods: { id: 'a'},
  name: '2'
}

const test3: MyFilteredDto = {
  prods: null, // type error
  name: '3',
}

WithNullableType 属性基本上只是表示对象上的给定属性可以为 null。

Playground Link

答案 1 :(得分:1)

首先,您可以使用 --config=CONFIG 并将该字段再次设为不可为空。如另一个答案所示,您当然可以创建自己的实用程序类型来处理此问题。

Omit

Playground Link