Languages
[Edit]
EN

TypeScript - remove function from object

0 points
Created by:
Lillie-Rose-Finnegan
489

In TypeScript, you shouldn't remove existing functions from objects as this can lead to errors.

Such things can be solved by deleting the object to a different type (e.g. omitting a property) or creating a new object that does not contain the method that we want to omit.

Practical examples

Example 1

interface Student {
  name: string;
  print(): void;
}

const studentObject: Student = {
  name: 'John',
  print: function () {
    console.log('text...');
  },
};

// create new type that has no print method
type Student2 = Omit<Student, 'print'>;

// create reference to Student object omitting print method
const studentObject2 = studentObject as Student2;

Example 2

interface Student {
  name: string;
  print(): void;
}

const student: Student = {
  name: 'John',
  print: function () {
    console.log('text...');
  },
};

// create reference to Student object omitting print method
const student2 = student as Omit<Student, 'print'>;

Note:

student2 contains print() method, but the type it was cast to does not.

 Example 3

interface Student {
  name: string;
  print(): void;
}

const student: Student = {
  name: 'John',
  print: function () {
    console.log('text...');
  },
};

class StudentData {
  public name: string;

  constructor(student: Student) {
    this.name = student.name;
  }
}

const student3 = new StudentData(student);

Example 4

interface Student {
  name: string;
  print(): void;
}

const student: Student = {
  name: 'John',
  print: function () {
    console.log('text...');
  },
};

class StudentData {
  constructor(public name: string, public age: number) {}
}

const student4 = new StudentData('John', 22);

Alternative titles

  1. TypeScript - how to remove function from object?
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join