簡體   English   中英

在 TypeScript 如何定義一個(通用)類型,其中定義了一些屬性(但仍然可以為空)?

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

我想要(但我不能)定義一個泛型類型,它使Product的某些屬性已定義,但仍然可以為 null。 我正在考慮自己仍在學習 TypeScript ......但對我來說似乎很難。

class Product {
  id: number | string;
  name: null | string;
  variants?: ProductVariant[];
}

這是我到目前為止所做的:

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

正如 NirG 在問題評論中所建議的那樣,只需使用Pick實用程序類型,但結合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[]; }

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM