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

后端 未结 3 1422
小蘑菇
小蘑菇 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:50

    I've found a way to exclude all properties that match a given type, thanks to this article: https://medium.com/dailyjs/typescript-create-a-condition-based-subset-types-9d902cea5b8c

    I made a few adaptations, but here is the details:

    // 1 Transform the type to flag all the undesired keys as 'never'
    type FlagExcludedType = { [Key in keyof Base]: Base[Key] extends Type ? never : Key };
        
    // 2 Get the keys that are not flagged as 'never'
    type AllowedNames = FlagExcludedType[keyof Base];
        
    // 3 Use this with a simple Pick to get the right interface, excluding the undesired type
    type OmitType = Pick>;
        
    // 4 Exclude the Function type to only get properties
    type ConstructorType = OmitType;
    

    Try It

    There might be a simpler way, I've tried playing with ConstructorParameters and defining a constructor signature but without results.

    Update

    Found an equivalent while browsing the typescript documentation here: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types

    type NonFunctionPropertyNames = {
      [K in keyof T]: T[K] extends Function ? never : K;
    }[keyof T];
    type NonFunctionProperties = Pick>;
    

    It's a bit less verbose since the omitted type is not generic, but it's the same idea.

提交回复
热议问题