[英]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.