首页 > 解决方案 > 从对象类型中排除函数类型

问题描述

在以下代码摘录中:

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

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

游乐场链接。

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

我怎样才能只允许该类型中的非函数类型MyCustomType

PS:User不应该过滤掉的类型。

标签: typescript

解决方案


这是 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[] }

快速搜索 Typescript Github repo发现此类型当前不是内置实用程序类型(与未记录的类型Parameters<T>ConstructorParameters<T>不同),因此您必须NonFunctionProperties自己定义等价物。


推荐阅读