Issue
I built an array of objects with this type
export type MyDto = { prods: {id:string} | null } & {name: string};
than I filter it to get rid of null type so I've got this type
export type MyFilteredDto = { prods: {id:string} } & {name: string};
is there a way to avoid duplication (not using an other type) using for instance an utility type?
Solution
You can use a type to specify that a property of a type is nullable:
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',
}
The WithNullableType
prop basically just says that a given property on an object is nullable.
Answered By - OliverRadini
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.