我用这种类型构建了一个对象数组
export type MyDto = { prods: {id:string} | null } & {name: string};
然后我过滤它以摆脱空类型,所以我得到了这种类型
export type MyFilteredDto = { prods: {id:string} } & {name: string};
有没有办法避免重复(不使用其他类型),例如使用实用程序类型?
答案 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。
答案 1 :(得分:1)