首页 > 解决方案 > 打字稿避免交叉路口中可空值的重复类型

问题描述

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

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

比我过滤它以摆脱空类型,所以我有这种类型

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

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

标签: typescript

解决方案


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

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道具基本上只是说对象上的给定属性是可以为空的。

游乐场链接


推荐阅读