简体   繁体   English

在 TypeScript 如何定义一个(通用)类型,其中定义了一些属性(但仍然可以为空)?

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

Playground Link 游乐场链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何定义通用类型:类型为属性名称 typescript - How can I define Generic type : type as property name typescript TypeScript:如何细化其中一个属性可能是 null 的类型 - TypeScript: How to refine a type where one of it's properties is probably null 如何在 Typescript 中定义具有一些可选指定属性以及一些必需指定属性的类型 - How to define a type with some optional specified properties along side some required specified ones in Typescript 如何在 TypeScript 中定义通用匿名 function 类型? - How to define a generic anonymous function type in TypeScript? 如何在 Typescript 中定义通用类型保护? - How to define a generic Type Guard in Typescript? 如何使用 keyof 属性定义通用打字稿类型? - How to define generic typescript type with keyof property? 如何为具有通用键的字典定义 typescript 类型? - How to define a typescript type for a dictionary with generic keys? 如何在typescript中定义的流中定义映射类型 - How to define mapped type in flow as defined in typescript 如何在TypeScript中使用动态属性定义对象的类型 - How to define type for object with dynamic properties in TypeScript 在 Typescript 中,如何定义/键入具有附加属性的 function - In Typescript, how to define/type a function with additional properties
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM