Typescript: Защита свойств и методов
В некоторых случаях свойства и методы в классе создаются только для внутреннего использования. Разработчики не хотят давать возможность вызывать их снаружи, иначе их случайно могут начать использовать, что не планировалось.
В языках с классами принято разделять свойства на публичные, приватные и защищенные. Первые доступны для всех, вторые могут использоваться только внутри класса, а третьи — внутри класса и в его наследниках. В этом уроке разберем каждый из этих видов.
Публичные свойства
По умолчанию в TypeScript все свойства публичные. Это можно обозначить явно с помощью ключевого слова public:
class Point {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
public someMethod() {
// some logic
}
}Приватные свойства
Также свойства можно сделать приватными. Тогда пропадет возможность обращаться к ним снаружи напрямую:
class Point {
private x: number;
private y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const p = new Point(10, 8);
p.x; // Property 'x' is private and only accessible within class 'Point'.
p.y; // Property 'y' is private and only accessible within class 'Point'.Защищенные свойства
И наконец, свойства можно сделать защищенными. Это значит, что они доступны внутри класса и в наследниках:
class Point {
protected x: number;
protected y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
class Point3D extends Point {
protected z: number;
constructor(x: number, y: number, z: number) {
super(x, y);
this.z = z;
}
public getCoordinates() {
return [this.x, this.y, this.z]; // OK
}
}
const p = new Point3D(10, 8, 5);
p.x; // Property 'x' is protected and only accessible within class 'Point' and its subclasses.
p.y; // Property 'y' is protected and only accessible within class 'Point' and its subclasses.
p.z; // Property 'z' is protected and only accessible within class 'Point3D' and its subclasses.Задание
Реализуйте класс ImageCustomFile, который расширяет (extends) класс CustomFile дополнительными приватными полями: width, height. Также переопределите метод toString(). Теперь он должен дополнительно выводить <width>x<height>.
const imageCustomFile = new ImageCustomFile({
name: 'image.png',
size: 100,
width: 200,
height: 300,
});
console.log(imageCustomFile.toString()); // image.png (100 bytes) 200x300Чтобы вызвать метод родительского класса, используйте super.toString().
Typescript: Защита свойств и методов
В некоторых случаях свойства и методы в классе создаются только для внутреннего использования. Разработчики не хотят давать возможность вызывать их снаружи, иначе их случайно могут начать использовать, что не планировалось.
В языках с классами принято разделять свойства на публичные, приватные и защищенные. Первые доступны для всех, вторые могут использоваться только внутри класса, а третьи — внутри класса и в его наследниках. В этом уроке разберем каждый из этих видов.
Публичные свойства
По умолчанию в TypeScript все свойства публичные. Это можно обозначить явно с помощью ключевого слова public:
class Point {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
public someMethod() {
// some logic
}
}Приватные свойства
Также свойства можно сделать приватными. Тогда пропадет возможность обращаться к ним снаружи напрямую:
class Point {
private x: number;
private y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const p = new Point(10, 8);
p.x; // Property 'x' is private and only accessible within class 'Point'.
p.y; // Property 'y' is private and only accessible within class 'Point'.Защищенные свойства
И наконец, свойства можно сделать защищенными. Это значит, что они доступны внутри класса и в наследниках:
class Point {
protected x: number;
protected y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
class Point3D extends Point {
protected z: number;
constructor(x: number, y: number, z: number) {
super(x, y);
this.z = z;
}
public getCoordinates() {
return [this.x, this.y, this.z]; // OK
}
}
const p = new Point3D(10, 8, 5);
p.x; // Property 'x' is protected and only accessible within class 'Point' and its subclasses.
p.y; // Property 'y' is protected and only accessible within class 'Point' and its subclasses.
p.z; // Property 'z' is protected and only accessible within class 'Point3D' and its subclasses.Задание
Реализуйте класс ImageCustomFile, который расширяет (extends) класс CustomFile дополнительными приватными полями: width, height. Также переопределите метод toString(). Теперь он должен дополнительно выводить <width>x<height>.
const imageCustomFile = new ImageCustomFile({
name: 'image.png',
size: 100,
width: 200,
height: 300,
});
console.log(imageCustomFile.toString()); // image.png (100 bytes) 200x300Чтобы вызвать метод родительского класса, используйте super.toString().
Ваше упражнение проверяется по этим тестам
import { expect, test } from 'vitest';
import ImageCustomFile from './index';
test('ImageCustomFile', () => {
const imageCustomFile = new ImageCustomFile({
name: 'image.png',
size: 100,
width: 200,
height: 300,
});
expect(imageCustomFile.toString()).toBe('image.png (100 bytes) 200x300');
const imageCustomFile2 = new ImageCustomFile({
name: 'image2.png',
size: 400,
width: 500,
height: 600,
});
expect(imageCustomFile2.toString()).toBe('image2.png (400 bytes) 500x600');
// @ts-expect-error - private property
expect(imageCustomFile2.name).toBe('image2.png');
// @ts-expect-error - private property
expect(imageCustomFile2.size).toBe(400);
// @ts-expect-error - private property
expect(imageCustomFile2.width).toBe(500);
// @ts-expect-error - private property
expect(imageCustomFile2.height).toBe(600);
});Решение учителя откроется через:
20:00
