[英]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.我想要(但我不能)定义一个泛型类型,它使
Product
的某些属性已定义,但仍然可以为 null。 I'm considering myself still learning TypeScript... but it seems so hard to me.我正在考虑自己仍在学习 TypeScript ......但对我来说似乎很难。
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
:正如 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.