Home > OS >  How to omit methods from a class type
How to omit methods from a class type

Time:03-31

Given the following class declaration, how to get a type that excludes the method getSomething? The example below gives an error because it expect the object to have the method getSomething

class Test {
    public readonly label: string = '';
    public constructor(opts?: Test) {
    Object.assign(this, opts);
    }

    public getSomething(): Array<number> {
        return [];
    }

}

const test: Test= new Test({label: 'label'}) // an error is thrown

CodePudding user response:

You can remove functions from a type, but this will unfortunately remove fields that are functions as well:

type OmitFunctions<T> = {
    [P in keyof T as T[P] extends Function ? never : P]: T[P]
}

class Test {
    public readonly label: string = '';
    public constructor(opts?: OmitFunctions<Test>) {
        Object.assign(this, opts);
    }

    public getSomething(): Array<number> {
        return [];
    }

}

const test: Test = new Test({ label: 'label' }) 

Playground Link

You can create a type where you add back any function fields, but it would be a manual process:

type OmitFunctions<T, Exclude extends keyof T = never> = {
    [P in keyof T as T[P] extends Function ? P extends Exclude ? P: never : P]: T[P]
}


class Test {
    public readonly label: string = '';
    public readonly fn!: () => string;
    public constructor(opts?: OmitFunctions<Test, 'fn'>) {
        Object.assign(this, opts);
    }

    public getSomething(): Array<number> {
        return [];
    }

}

const test: Test = new Test({ label: 'label', fn: () => "" }) 

Playground Link

CodePudding user response:

OmitProperties of ts-essentials can be used

import { OmitProperties} from 'ts-essentials';

public constructor(opts?: OmitProperties<Test, Function>) {
    Object.assign(this, opts);
}

CodePudding user response:

You can use the built-in Partial<T> generic type as follows.

class Test {
  public readonly label: string = "";

  public constructor(opts?: Partial<Test>) {
    Object.assign(this, opts);
  }

  public getSomething(): Array<number> {
    return [];
  }
}

const test: Test = new Test({ label: "label" }); // runs without error
  • Related