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.
Example 1
xxxxxxxxxx
1
interface Student {
2
name: string;
3
print(): void;
4
}
5
6
const studentObject: Student = {
7
name: 'John',
8
print: function () {
9
console.log('text...');
10
},
11
};
12
13
// create new type that has no print method
14
type Student2 = Omit<Student, 'print'>;
15
16
// create reference to Student object omitting print method
17
const studentObject2 = studentObject as Student2;
Example 2
xxxxxxxxxx
1
interface Student {
2
name: string;
3
print(): void;
4
}
5
6
const student: Student = {
7
name: 'John',
8
print: function () {
9
console.log('text...');
10
},
11
};
12
13
// create reference to Student object omitting print method
14
const student2 = student as Omit<Student, 'print'>;
Note:
student2
containsprint()
method, but the type it was cast to does not.
Example 3
xxxxxxxxxx
1
interface Student {
2
name: string;
3
print(): void;
4
}
5
6
const student: Student = {
7
name: 'John',
8
print: function () {
9
console.log('text...');
10
},
11
};
12
13
class StudentData {
14
public name: string;
15
16
constructor(student: Student) {
17
this.name = student.name;
18
}
19
}
20
21
const student3 = new StudentData(student);
xxxxxxxxxx
1
interface Student {
2
name: string;
3
print(): void;
4
}
5
6
const student: Student = {
7
name: 'John',
8
print: function () {
9
console.log('text...');
10
},
11
};
12
13
class StudentData {
14
constructor(public name: string, public age: number) {}
15
}
16
17
const student4 = new StudentData('John', 22);