Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude function types from an object type

Tags:

typescript

In the following excerpt of code:

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

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

Playground link.

Is there a way to remove only the function types of that interface? I've created the MyCustomType type, but I did not find a way to remove the function types, such as getInfo.

How can I allow only non-functions types in that MyCustomType type?

P.S.: Types such as User should not be filtered out.

like image 800
Luiz Felipe Avatar asked May 07 '26 18:05

Luiz Felipe


1 Answers

This is one of the listed examples of the Distributive Conditional Types examples on the "Advanced Types" page of the Typescript handbook.

Conditional types are particularly useful when combined with mapped 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 reveals that this type is not currently a built-in utility type (unlike the undocumented types Parameters<T> and ConstructorParameters<T>), so you'll have to define the NonFunctionProperties equivalent yourself.

like image 129
Jeff Bowman Avatar answered May 11 '26 14:05

Jeff Bowman