Что такое TypeScript?
TypeScript — это надмножество JavaScript со статическими типами, разработанное Microsoft и предназначенное для улучшения процесса разработки крупномасштабных приложений JavaScript. Он добавляет в JavaScript необязательную статическую типизацию, интерфейсы, классы, декораторы и модули, позволяя разработчикам писать более надежный и удобный код. TypeScript компилируется в обычный JavaScript и широко используется в популярных средах и библиотеках JavaScript, предоставляя улучшенные инструменты и проверку типов для разработки JavaScript.
Часто используемый синтаксис и концепции TypeScript:
- Объявления переменных:
let num: number = 42; let str: string = 'Hello'; let bool: boolean = true; let arr: number[] = [1, 2, 3]; let tuple: [string, number] = ['foo', 42]; let obj: { name: string, age: number } = { name: 'John', age: 30 };
2. Аннотации типов:
function greet(name: string): string { // function with type annotations for parameters and return value return "Hello, " + name; }
3. Интерфейсы:
interface Animal { name: string; species: string; age?: number; // Optional property } // Usage const dog: Animal = { name: "Buddy", species: "Dog" }; console.log(dog.name); // Output: Buddy console.log(dog.species); // Output: Dog
В этом примере свойство age
является необязательным, поэтому его присутствие в объекте dog
не обязательно.
Интерфейсы в TypeScript также могут расширять другие интерфейсы, позволяя вам наследовать свойства и методы от других интерфейсов. Вот пример:
interface Animal { name: string; species: string; } interface Mammal extends Animal { numberOfLegs: number; isWarmBlooded: boolean; } // Usage const dog: Mammal = { name: "Buddy", species: "Dog", numberOfLegs: 4, isWarmBlooded: true }; console.log(dog.name); // Output: Buddy console.log(dog.species); // Output: Dog console.log(dog.numberOfLegs); // Output: 4 console.log(dog.isWarmBlooded); // Output: true
В этом примере мы определяем интерфейс Mammal
, который расширяет интерфейс Animal
, наследуя его свойства name
и species
и добавляя два дополнительных свойства numberOfLegs
и isWarmBlooded
.
4. Классы:
Класс TypeScript, демонстрирующий различные функции, включая свойства, методы, наследование, модификаторы доступа и статические члены:
class Animal { private name: string; protected species: string; static numberOfLegs: number = 4; constructor(name: string, species: string) { this.name = name; this.species = species; } public makeSound(): void { console.log('Animal is making a sound.'); } protected move(): void { console.log('Animal is moving.'); } private sleep(): void { console.log('Animal is sleeping.'); // private method } static getInfo(): string { return `This is an animal with ${Animal.numberOfLegs} legs.`; } } class Dog extends Animal { constructor(name: string) { super(name, 'Dog'); // calling the constructor of the parent class } public makeSound(): void { console.log('Dog is barking.'); // overriding makeSound() of parent class } public move(): void { super.move(); // calling move() of parent class console.log('Dog is running.'); // extending move() of parent class } public playFetch(): void { console.log('Dog is playing fetch.'); } } // Create objects and invoke class methods const animal = new Animal('Animal', 'Unknown'); console.log(animal.species); // Error: species is protected and cannot be accessed outside the class and its subclasses animal.makeSound(); // "Animal is making a sound." console.log(Animal.getInfo()); // "This is an animal with 4 legs." const dog = new Dog('Buddy'); console.log(dog.species); // "Dog" dog.makeSound(); // "Dog is barking." dog.move(); // "Animal is moving." "Dog is running." dog.playFetch(); // "Dog is playing fetch."
В этом примере у нас есть базовый класс Animal
со свойствами, методами с разными модификаторами доступа (public
, protected
и private
) и статический член numberOfLegs
. Класс Dog
расширяет класс Animal
, переопределяя и расширяя его методы. Мы также создаем объекты обоих классов и вызываем их методы. Обратите внимание, что доступ к членам protected
и private
ограничен внутри класса и его подклассов.
5. Дженерики:
function identity<T>(arg: T): T { // generic function return arg; } const num: number = identity(5); // T is inferred as number const str: string = identity("hello"); // T is inferred as string
6. Введите псевдонимы:
type Coordinate = { x: number, y: number }; // type alias for an object with x and y properties function printCoordinates(coord: Coordinate): void { console.log(`x: ${coord.x}, y: ${coord.y}`); }
7. Типы объединения и пересечения:
type NumberOrString = number | string; // union type function printNumberOrString(value: NumberOrString): void { console.log(value); } type PersonWithAddress = Person & { address: string }; // intersection type const personWithAddress: PersonWithAddress = { name: "Bob", age: 25, address: "123 Main St" };
8. Перечисления:
enum Color { Red, Green, Blue } const myColor: Color = Color.Green; console.log(myColor); // prints 1
9. Утверждение типа:
const someValue: any = "hello"; const strLength: number = (someValue as string).length; // type assertion to treat someValue as a string
Примечание. TypeScript — это надмножество JavaScript, поэтому вы также можете использовать большинство синтаксиса и функций JavaScript в TypeScript. В этом блоге рассматриваются некоторые особенности синтаксиса и концепции TypeScript.
Если этот пост был полезен, пожалуйста, несколько раз нажмите кнопку аплодисментов 👏, чтобы выразить свою поддержку автору 👇
Ссылка: