How to create a type excluding instance methods from a class in typescript?

后端 未结 3 1478
小蘑菇
小蘑菇 2021-02-05 17:19

Given a class, containing both properties and methods, I\'d like to derive a type that just contains its properties.

For example, if I define a class as follow:

         


        
3条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 17:56

    Given a class, containing both properties and methods, I'd like to derive a type that just contains its properties.

    From your example, it seems like you want the result to contain only fields (as opposed to only properties). Here is a type that picks out the fields from an object or class instance.

    type DataPropertyNames = {
      [K in keyof T]: T[K] extends Function ? never : K;
    }[keyof T];
    
    type DataPropertiesOnly = {
      [P in DataPropertyNames]: T[P] extends object ? DTO : T[P]
    };
    
    export type DTO = DataPropertiesOnly;
    

    I have used the acronym DTO to mean Data Transfer Object. Thank you to l00ser2410656 for this playground demo.

提交回复
热议问题