Home > other >  In TypeScript how to define a (generic) type where some properties are defined (but still can be nul
In TypeScript how to define a (generic) type where some properties are defined (but still can be nul

Time:01-04

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] }>

enter image description here

// 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]> }>

enter image description here

// 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[]; }

Playground Link

  • Related