Skip to content

Commit b97f119

Browse files
committed
Update ts-basics.md
1 parent fd032db commit b97f119

1 file changed

Lines changed: 344 additions & 0 deletions

File tree

TypeScript/Basics/ts-basics.md

Lines changed: 344 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,344 @@
1+
# TypeScript basics
2+
3+
1. [Basic types](#basic-types)
4+
2. [Custom types and interfaces](#custom-types-and-interfaces)
5+
3. [Functions](#functions)
6+
4. [Classes](#classes)
7+
5. [Enums](#enums)
8+
6. [Generics](#generics)
9+
10+
---
11+
12+
## Basic types
13+
14+
- **boolean** <br>
15+
16+
```ts
17+
const isLoading: boolean = true;
18+
```
19+
20+
- **string** <br>
21+
22+
```ts
23+
const message: string = "Hello World!";
24+
```
25+
26+
- **number** <br>
27+
28+
```ts
29+
const year: number = 2022;
30+
const exp: number = 2.718;
31+
```
32+
33+
- **array** <br>
34+
_There are some ways to declare an array_
35+
36+
```ts
37+
const nums: number[] = [1, 2, 3, 4, 5]; // only numbers
38+
const products: Array<string> = ["bread", "milk"]; // only strings
39+
const someValues: [string, boolean] = ["ts", true]; // only 1 string and 1 boolean
40+
```
41+
42+
- **any** <br>
43+
_Allows to disable type checking, as a result the variable can dynamically change it's type. Avoid `any` in your code._
44+
45+
```ts
46+
let value: any = "this is string";
47+
value = 107;
48+
value = false;
49+
value = [1, 2, "a", "b", true];
50+
```
51+
52+
---
53+
54+
## Custom types and interfaces
55+
56+
- **Type Aliases** <br>
57+
_Good for describing types in simple objects or for variables that may have more than one type._
58+
59+
```ts
60+
type Animal = {
61+
name: string;
62+
age: number;
63+
};
64+
65+
const animal: Animal = {
66+
name: "Fluffy",
67+
age: 4,
68+
};
69+
```
70+
71+
```ts
72+
// extending a type
73+
type Cat = Animal & {
74+
color: string;
75+
};
76+
```
77+
78+
```ts
79+
// value with 2 types
80+
type ID = string | number;
81+
82+
const userId: ID = 239053;
83+
const itemId: ID = "A934VL";
84+
```
85+
86+
- **Interfaces** <br>
87+
_An interface declaration is another way to name an object type. Interfaces support a more convenient extension and are used more often._
88+
89+
```ts
90+
interface IPerson {
91+
firstName: string;
92+
lastName?: string; // an optional parameter
93+
gender: "female" | "male"; // only certain values
94+
isMarried: boolean;
95+
}
96+
97+
//Extending an interface
98+
interface IWorker extends IPerson {
99+
job: string;
100+
}
101+
102+
const someone: IWorker = {
103+
firstName: "Alex",
104+
gender: "male",
105+
isMarried: true,
106+
job: "engineer",
107+
};
108+
```
109+
110+
---
111+
112+
## Functions
113+
114+
- **Basic usage** <br>
115+
_We can describe the types of function arguments as well as the return value_
116+
117+
```ts
118+
// type "void" means that our function does not return anything
119+
function logInfo(name: string, age: number): void {
120+
console.log(`My name is ${name}, I'm ${age} y.o.`);
121+
}
122+
123+
// Arrow function
124+
const square = (x: number): number => x * x;
125+
```
126+
127+
- **Default arguments** <br>
128+
_When default parameters are specified, their types are automatically determined by the passed values_
129+
130+
```ts
131+
function getNumbers(max: number = 99, min = 1): void {}
132+
```
133+
134+
- **Optional arguments** <br>
135+
136+
```ts
137+
function greeting(name?: string): void {
138+
if (name) {
139+
console.log(`Welcome, ${name}!`);
140+
} else {
141+
console.log(`Welcome, annonymous user!`);
142+
}
143+
}
144+
```
145+
146+
- **Unlimited arguments** <br>
147+
_You can describe an indefinite number of arguments of the same type using spread operator_
148+
149+
```ts
150+
const logValues = (x: number, ...values: string[]): void =>
151+
console.log(x, ...values);
152+
153+
logValues(77, "one", "two", "three", "...");
154+
```
155+
156+
- **Function type** <br>
157+
_Use function type to describe methods_
158+
159+
```ts
160+
interface IService {
161+
calcSum: (a: number, b: number) => number;
162+
getBalance: () => string;
163+
sendFeedback: (mes: string) => void;
164+
}
165+
```
166+
167+
---
168+
169+
## Classes
170+
171+
- **Modifiers** <br>
172+
_Various modifiers allow you to define the scope of variables and methods_
173+
174+
```ts
175+
class Example {
176+
constructor(a: number, b: number) {
177+
this.a = a;
178+
this.b = b;
179+
}
180+
181+
/* prevents assignments to the field outside
182+
of the constructor */
183+
readonly a: number;
184+
185+
/* visible only inside classes inherited from
186+
the current class (not from outside) */
187+
protected b: number;
188+
189+
/* visible only inside current class
190+
(not from inherited and outside) */
191+
private secret = "hello";
192+
193+
alert = () => {};
194+
}
195+
```
196+
197+
- **Extending a class** <br>
198+
_Classes can easily be extended by adding new variables/methods. This also supports overriding methods, but in a way that ensures backward compatibility._
199+
200+
```ts
201+
class NewExmaple extends Example {
202+
constructor(a: number, b: number, c: number) {
203+
super(a, b);
204+
this.c = c;
205+
}
206+
207+
c: number;
208+
209+
alert(name?: string) {
210+
console.log(`Hello ${name}`);
211+
}
212+
}
213+
```
214+
215+
- **Abstract classes** <br>
216+
_Abstract classes/methods do not allow you to create instances, but only serve for expansion_
217+
218+
```ts
219+
abstract class Somebody {
220+
hello(): void {
221+
console.log("Hello!");
222+
}
223+
}
224+
225+
class User extends Somebody {
226+
introduce(): void {
227+
console.log("I am User!");
228+
}
229+
}
230+
231+
const user = new User();
232+
user.hello(); // "Hello!"
233+
```
234+
235+
- **Interface implementation** <br>
236+
_Interfaces can be used to describe classes_
237+
238+
```ts
239+
interface ITest {
240+
value: string;
241+
getNumber: () => number;
242+
}
243+
244+
class Test implements ITest {
245+
value = "test";
246+
getNumber = () => 7;
247+
}
248+
```
249+
250+
---
251+
252+
## Enums
253+
254+
- **Numeric enums** <br>
255+
_Enums allow to define a set of named constants. Numeric enums automatically assign numbers to named constants._
256+
257+
```ts
258+
enum Roles {
259+
user, // Roles.user = 0
260+
moderator, // Roles.moderator = 1
261+
admin, // Roles.admin = 2
262+
}
263+
264+
enum Services {
265+
GitHub = 10, // Services.Github = 10
266+
Google, // Services.Google = 11
267+
Amazon, // Services.Amazon = 12
268+
}
269+
```
270+
271+
- **String & mixed enums** <br>
272+
273+
```ts
274+
enum Bool {
275+
yes = "YES",
276+
no = "NO"
277+
}
278+
279+
enum Server {
280+
host = "server.com"
281+
port = 5432
282+
}
283+
```
284+
285+
---
286+
287+
## Generics
288+
289+
- **Basic usage** <br>
290+
_Generics allows to create a component that can work over a variety of types rather than a single one_
291+
292+
```ts
293+
function test<T>(value: T): T {
294+
return value;
295+
}
296+
// "T" will be replaced by the type we specified
297+
298+
test<string>("Hello World");
299+
test<number>(2022);
300+
test<boolean>(true);
301+
```
302+
303+
- **Type checking** <br>
304+
_You can safely use type checking with the `typeof` operator to execute the appropriate logic_
305+
306+
```ts
307+
function logger<T>(value: T): void {
308+
if (typeof value == "string") {
309+
// we are pretty sure that only strings will get here
310+
console.log(value.toLocaleUpperCase());
311+
// therefore, we can use string methods
312+
} else if (typeof value == "number") {
313+
console.log(value.toFixed(2));
314+
} else {
315+
console.log(`${value} has the ${typeof value} type`);
316+
}
317+
}
318+
319+
logger<string>("Hello World"); // "HELLO WORLD"
320+
logger<number>(2022); // 2022.00
321+
logger<boolean>(true); // "true has the boolean type"
322+
```
323+
324+
- **Multiple generics** <br>
325+
_You can pass multiple generics, for example, to describe different input and output types in functions_
326+
327+
```ts
328+
interface IService {
329+
process: <T, S>(data: T) => S;
330+
}
331+
```
332+
333+
- **Extending generic type** <br>
334+
335+
```ts
336+
interface IValue {
337+
info: string;
338+
}
339+
340+
function test<T extends IValue>(value: T): T {
341+
console.log(value.info);
342+
return value;
343+
}
344+
```

0 commit comments

Comments
 (0)