I want (but I can't) defined a generic type that make some properties of Product
defined, but still nullable. I'm considering myself still learning TypeScript... but it seems so hard to me.
class Product {
id: number | string;
name: null | string;
variants?: ProductVariant[];
}
Here is what I've done so far:
// Not good: undefined are still allowed
type Exploded<T, K extends string & keyof T>
= Omit<T, K> & Required<{ [key in K]: T[key] }>
// Not good: name is now not null
type Exploded<T, K extends string & keyof T>
= Omit<T, K> & Required<{ [key in K]: NonNullable<T[key]> }>
// Not good: does not handle null AND undefined
type Exploded<T, K extends string & keyof T>
= Omit<T, K> & Required<{
[key in K]: null extends T[key] ? T[key] :NonNullable<T[key]>
}>
CodePudding user response:
Just use Pick
utility type, as suggested by NirG in the question comments, but combined with Required
:
type Exploded<T, K extends keyof T> = Required<Pick<T, K>>;
type ExplodedProduct = Exploded<Product, 'id' | 'name' | 'variants'>;
// ^? { id: number | string; name: null | string; variants: ProductVariant[]; }