EN
TypeScript - remove function from object
0
points
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:
student2containsprint()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);