从对象类型中排除函数类型

时间:2019-10-02 22:57:40

标签: typescript

在以下代码摘录中:

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之类的类型。

2 个答案:

答案 0 :(得分:2)

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

  

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

     
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<T> and ConstructorParameters<T>不同),因此您必须自己定义NonFunctionProperties等效项。 / p>

答案 1 :(得分: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>>;

结果:

enter image description here