简体   繁体   中英

In TypeScript how to define a (generic) type where some properties are defined (but still can be null)?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM