【问题标题】:Exclude function types from an object type从对象类型中排除函数类型
【发布时间】:2019-10-03 10:21:18
【问题描述】:

在以下代码摘录中:

interface User {
  name: string;
  age: number;
  bestFriend: User;
  getInfo: () => any;
}

type MyCustomType = {
  [key in keyof User]: User[key]
};

Playground link.

有没有办法只删除该接口的函数类型?我已经创建了MyCustomType 类型,但是我没有找到删除函数类型的方法,例如getInfo

如何在 MyCustomType 类型中只允许非函数类型?

P.S.:User 等类型不应被过滤掉。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    这是Distributive Conditional Types 列出的示例之一 Typescript 手册的“高级类型”页面上的示例。

    条件类型在与映射类型结合使用时特别有用:

    type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
    type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;
    
    type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
    type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
    
    interface Part {
        id: number;
        name: string;
        subparts: Part[];
        updatePart(newName: string): void;
    }
    
    type T40 = FunctionPropertyNames<Part>;  // "updatePart"
    type T41 = NonFunctionPropertyNames<Part>;  // "id" | "name" | "subparts"
    type T42 = FunctionProperties<Part>;  // { updatePart(newName: string): void }
    type T43 = NonFunctionProperties<Part>;  // { id: number, name: string, subparts: Part[] }
    

    A quick search of the Typescript Github repo 表明此类型当前不是内置实用程序类型(与未记录的类型 Parameters&lt;T&gt; and ConstructorParameters&lt;T&gt; 不同),因此您必须自己定义 NonFunctionProperties 等效项。

    【讨论】:

      【解决方案2】:

      这是 Jeff 综合答案的简化版本和 playground link.

      interface User {
          name: string;
          age: number;
          bestFriend: User;
          getInfo: () => any
      }
      
      // Do not worry too much about understanding this 
      // until you're ready for advanced TypeScript.
      type FunctionPropertyNames<T> = { 
          [K in keyof T]: T[K] extends Function ? K : never 
      }[keyof T];
      
      type MyCustomType = Omit<User, FunctionPropertyNames<User>>;
      

      结果:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-01-07
        • 2015-03-24
        • 2021-01-10
        • 1970-01-01
        • 2019-10-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多