Warning: preg_grep(): Compilation failed: quantifier does not follow a repeatable item at offset 27 in /var/www/tg-me/post.php on line 75
Frontend | Вопросы собесов | Telegram Webview: easy_javascript_ru/1321 -
Telegram Group & Telegram Channel
🤔 На что можно заменить интерфейсы в js?

В JavaScript нет встроенной поддержки интерфейсов, как в TypeScript, Java или C#. Однако, их можно заменить несколькими способами, в зависимости от задачи.

🟠Использование JSDoc (аннотации типов)
Можно описывать структуру объектов с помощью @typedef и @param, что помогает при автодополнении и статическом анализе кода.
/**
* @typedef {Object} User
* @property {string} name
* @property {number} age
*/

/**
* @param {User} user
*/
function printUser(user) {
console.log(`Имя: ${user.name}, Возраст: ${user.age}`);
}

const person = { name: "Alice", age: 30 };
printUser(person); // Работает!


🟠Использование классов (Abstract Class Pattern)
Можно создать абстрактный класс с методами-заглушками, которые нужно реализовать в потомках.
class Animal {
constructor(name) {
if (new.target === Animal) {
throw new Error("Нельзя создать экземпляр абстрактного класса!");
}
this.name = name;
}

makeSound() {
throw new Error("Метод makeSound() должен быть переопределён!");
}
}

class Dog extends Animal {
makeSound() {
return "Гав-гав!";
}
}

const dog = new Dog("Бобик");
console.log(dog.makeSound()); // "Гав-гав!"

// const animal = new Animal("Лев"); // Ошибка!


🟠Проверка структуры объекта (Duck Typing)
Можно просто проверять, есть ли нужные методы и свойства у объекта перед использованием.
function useDevice(device) {
if (typeof device.turnOn !== "function") {
throw new Error("Объект должен иметь метод turnOn()");
}
device.turnOn();
}

const phone = { turnOn: () => console.log("Телефон включен!") };
useDevice(phone); // "Телефон включен!"

const invalidDevice = { power: true };
// useDevice(invalidDevice); // Ошибка: "Объект должен иметь метод turnOn()"


🟠Использование TypeScript (лучший вариант)
TypeScript добавляет поддержку интерфейсов в JavaScript.
interface User {
name: string;
age: number;
}

function printUser(user: User) {
console.log(`Имя: ${user.name}, Возраст: ${user.age}`);
}

const person: User = { name: "Alice", age: 30 };
printUser(person); // Работает!


Ставь 👍 и забирай 📚 Базу знаний
Please open Telegram to view this post
VIEW IN TELEGRAM
👍10



tg-me.com/easy_javascript_ru/1321
Create:
Last Update:

🤔 На что можно заменить интерфейсы в js?

В JavaScript нет встроенной поддержки интерфейсов, как в TypeScript, Java или C#. Однако, их можно заменить несколькими способами, в зависимости от задачи.

🟠Использование JSDoc (аннотации типов)
Можно описывать структуру объектов с помощью @typedef и @param, что помогает при автодополнении и статическом анализе кода.

/**
* @typedef {Object} User
* @property {string} name
* @property {number} age
*/

/**
* @param {User} user
*/
function printUser(user) {
console.log(`Имя: ${user.name}, Возраст: ${user.age}`);
}

const person = { name: "Alice", age: 30 };
printUser(person); // Работает!


🟠Использование классов (Abstract Class Pattern)
Можно создать абстрактный класс с методами-заглушками, которые нужно реализовать в потомках.
class Animal {
constructor(name) {
if (new.target === Animal) {
throw new Error("Нельзя создать экземпляр абстрактного класса!");
}
this.name = name;
}

makeSound() {
throw new Error("Метод makeSound() должен быть переопределён!");
}
}

class Dog extends Animal {
makeSound() {
return "Гав-гав!";
}
}

const dog = new Dog("Бобик");
console.log(dog.makeSound()); // "Гав-гав!"

// const animal = new Animal("Лев"); // Ошибка!


🟠Проверка структуры объекта (Duck Typing)
Можно просто проверять, есть ли нужные методы и свойства у объекта перед использованием.
function useDevice(device) {
if (typeof device.turnOn !== "function") {
throw new Error("Объект должен иметь метод turnOn()");
}
device.turnOn();
}

const phone = { turnOn: () => console.log("Телефон включен!") };
useDevice(phone); // "Телефон включен!"

const invalidDevice = { power: true };
// useDevice(invalidDevice); // Ошибка: "Объект должен иметь метод turnOn()"


🟠Использование TypeScript (лучший вариант)
TypeScript добавляет поддержку интерфейсов в JavaScript.
interface User {
name: string;
age: number;
}

function printUser(user: User) {
console.log(`Имя: ${user.name}, Возраст: ${user.age}`);
}

const person: User = { name: "Alice", age: 30 };
printUser(person); // Работает!


Ставь 👍 и забирай 📚 Базу знаний

BY Frontend | Вопросы собесов


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/easy_javascript_ru/1321

View MORE
Open in Telegram


Frontend | Вопросы собесов Telegram | DID YOU KNOW?

Date: |

That strategy is the acquisition of a value-priced company by a growth company. Using the growth company's higher-priced stock for the acquisition can produce outsized revenue and earnings growth. Even better is the use of cash, particularly in a growth period when financial aggressiveness is accepted and even positively viewed.he key public rationale behind this strategy is synergy - the 1+1=3 view. In many cases, synergy does occur and is valuable. However, in other cases, particularly as the strategy gains popularity, it doesn't. Joining two different organizations, workforces and cultures is a challenge. Simply putting two separate organizations together necessarily creates disruptions and conflicts that can undermine both operations.

The SSE was the first modern stock exchange to open in China, with trading commencing in 1990. It has now grown to become the largest stock exchange in Asia and the third-largest in the world by market capitalization, which stood at RMB 50.6 trillion (US$7.8 trillion) as of September 2021. Stocks (both A-shares and B-shares), bonds, funds, and derivatives are traded on the exchange. The SEE has two trading boards, the Main Board and the Science and Technology Innovation Board, the latter more commonly known as the STAR Market. The Main Board mainly hosts large, well-established Chinese companies and lists both A-shares and B-shares.

Frontend | Вопросы собесов from us


Telegram Frontend | Вопросы собесов
FROM USA