interface User {
name: string;
age: number;
}
let user: User = {
name: "Bob",
age: 20, // omitting the `age` property or a assigning a different type instead of a number would throw an error
};
interface User {
name: string;
description: string;
age: number;
email: string;
}
// removes the `email` property from the User interface
type UserPreview = Omit<User, "email">;
const userPreview: UserPreview = {
name: "Bob",
description: "Awesome guy",
age: 20,
};
enum UserType {
Guest = "G",
Verified = "V",
Admin = "A",
}
const userType: UserType = UserType.Verified;
function addNumbers(x: number, y: number): number {
return x + y;
}
addNumbers(1, 2); // returns 3
const addNumbers = (x: number, y: number): number => {
return x + y;
};
addNumbers(1, 2); // returns 3
// reading/writing before a `let` variable is declared
console.log("age", age); // Compiler Error: error TS2448: Block-scoped variable 'age' used before its declaration
age = 20; // Compiler Error: error TS2448: Block-scoped variable 'age' used before its declaration
let age: number;
// accessing `let` variable outside it's scope
function user(): void {
let name: string;
if (true) {
let email: string;
console.log(name); // OK
console.log(email); // OK
}
console.log(name); // OK
console.log(email); // Compiler Error: Cannot find name 'email'
}
// reassigning a `const` variable
const age: number = 20;
age = 30; // Compiler Error: Cannot assign to 'age' because it is a constant or read-only property
// declaring a `const` variable without initialization
const name: string; // Compiler Error: const declaration must be initialized
printName(name: string): void {
console.log(name);
}
const printer = printName('Will');
console.log(printer); // logs "undefined"
const error = (): never => {
throw new Error("");
};
class User {
private username; // only accessible inside the `User` class
// only accessible inside the `User` class and its subclassprotected updateUser(): void {}
// accessible from any locationpublic getUser() {}
}
Property '<property-name>' is private and only accessible within class '<class-name>'.
function updateUser<Type>(arg: Type): Type {
return arg;
}
// explicitly specifying the type
let user = updateUser<string>("Bob");
// type argument inference
let user = updateUser("Bob");
invokeCallback(callback: any): void {
callback();
}
invokeCallback(callback: unknown): void {
if (typeof callback === 'function') {
callback();
}
}
A extends B ? X : Y
interface B {
name: string,
email: string
}
interface C {
name: string,
age: number
}
type A = B | C;
interface B {
name: string,
email: string
}
interface C {
name: string,
age: number
}
type A = B & C;
class User {
name: string;
age: number;
}
// John will contain name and age from the User class
class John extends User {}
// this will result in an error as Bob doesn't have all the properties that
// the User class has
class Bob implements User {}
// This is valid as Mike satisfies the "contract" specified by the
// User class
class Mike implements User {
name = 'Mike';
age = 25
}
const user = {
personalInfo: {
name: 'John'
}
}
// without optional chaining
const name = user && user.personalInfo && user.personalInfo.name || undefined;
// with optional chaining
const name = user?.personalInfo?.name;
abstract class Vehicle {
abstract drive(): void;
startEngine(): void {
console.log('Engine starting...');
}
}
class Car extends Vehicle {
drive(): void {
console.log('Driving in a car');
}
}
class Bike extends Vehicle {
drive(): void {
console.log('Driving on a bike');
}
}
// using the `as` keyword
const name: string = person.name as string;
// using `<>`
const name: string = <string>person.name;
let name = 'john'
window.onmousedown = function(mouseEvent) {
console.log(mouseEvent.button); // OK
console.log(mouseEvent.person); // Error
};
print(message: string): void;
print(message: string[]): void;
print(message: unknown): void {if (typeof message === 'string') {
console.log(message);
} else if (Array.isArray(message)) {
message.forEach((individualMessage) => {
console.log(individualMessage);
});
} else {
throw new Error('unable to print');
}
}
print('Single message');
// Console Output:
// Single message
print(['First message', 'Second message']);
// Console Output
// First message
// Second message
Наше ИТ кадровое агентство предлагает вам найти разработчиков менее чем за 2 недели. Свяжитесь с нами сегодня, чтобы узнать больше о том, как мы можем помочь масштабировать ваш следующий проект до новых высот. Мы гарантируем поиск самого сильного, а не самого дорого кандидата. За 10 лет в подборе it специалистов, мы закрыли 5500+ вакансий и собрали 25+ команд с нуля. Убедитесь сами и ознакомьтесь с отзывами клиентов о нашем рекрутинговом агентстве! Нужно больше референсов? Напишите нам в телеграмм.