You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
There are a few things that TypeScript prevents you from doing out of the box e.g. using a variable that *isn't ever declared* (of course you can use a *declaration file* for external systems).
3
+
Є кілька речей, які TypeScript не дозволяє вам робити з коробки, наприклад. використовуючи змінну, яка *ніколи не оголошується* (звичайно, ви можете використовувати *файл декларації* для зовнішніх систем).
4
4
5
-
That said, traditionally programming languages have a hard boundary between what is and isn't allowed by the type system. TypeScript is different in that it gives you control over where you put the slider. This is really to allow you to use the JavaScript you know and love with as much safety as**you**want. There are lots of compiler options to control exactly this slider so let's have a look.
5
+
Тим не менш, традиційні мови програмування мають жорстку межу між тим, що дозволено і заборонено системою типів. TypeScript відрізняється тим, що він дає вам контроль над тим, де розмістити повзунок. Це дійсно для того, щоб дозволити вам використовувати JavaScript, який ви знаєте і любите, з такою безпечністю, як**Ви**хочете. Існує багато параметрів компілятора для керування саме цим повзунком, тому давайте подивимося.
6
6
7
7
## Boolean Options
8
8
9
-
`compilerOptions` that are`boolean` can be specified as `compilerOptions`in`tsconfig.json`:
9
+
`compilerOptions`, які є`boolean`, можна вказати як `compilerOptions`у`tsconfig.json`:
10
10
11
11
```json
12
12
{
@@ -16,12 +16,12 @@ That said, traditionally programming languages have a hard boundary between what
16
16
}
17
17
```
18
18
19
-
or on the command line
19
+
чи в командному рядку
20
20
21
21
```sh
22
22
tsc --someBooleanOption
23
23
```
24
24
25
-
> All of these are`false` by default.
25
+
> Усе це за замовчуванням`false`.
26
26
27
-
Click [here](https://www.typescriptlang.org/docs/handbook/compiler-options.html) to see all compiler options.
27
+
Натисніть [тут](https://www.typescriptlang.org/docs/handbook/compiler-options.html), щоб переглянути всі параметри компілятора.
Copy file name to clipboardExpand all lines: docs/options/noImplicitAny.md
+5-5
Original file line number
Diff line number
Diff line change
@@ -1,34 +1,34 @@
1
1
# noImplicitAny
2
2
3
-
There are some things that cannot be inferred or inferring them might result in unexpected errors. A fine example is function arguments. If you don't annotate them, its unclear what should and shouldn't be valid e.g.
3
+
Є деякі речі, про які неможливо зробити висновок, або їх висновок може призвести до несподіваних помилок. Гарним прикладом є аргументи функції. Якщо ви не анотуєте їх, незрозуміло, що має бути дійсним, а що ні.
4
4
5
5
```ts
6
6
function log(someArg) {
7
7
sendDataToServer(someArg);
8
8
}
9
9
10
-
//What arg is valid and what isn't?
10
+
//Який аргумент вірний а який ні?
11
11
log(123);
12
12
log('hello world');
13
13
```
14
14
15
-
So if you don't annotate some function argument, TypeScript assumes`any`and moves on. This essentially turns off type checking for such cases, which is what a JavaScript dev would expect. But this can catch people that want high safety off guard. Hence there is an option, `noImplicitAny`, that when switched on will flag the cases where the type cannot be inferred e.g.
15
+
Отже, якщо ви не анотуєте якийсь аргумент функції, TypeScript припускає`any`і йде далі. По суті, це вимикає перевірку типу для таких випадків, чого очікував би розробник JavaScript. Але це може застати людей, які хочуть високої безпеки, зненацька. Таким чином, існує опція `noImplicitAny`, яка після ввімкнення позначатиме випадки, коли тип не можна визначити, наприклад.
16
16
17
17
```ts
18
18
function log(someArg) { // Error : someArg has an implicit `any` type
19
19
sendDataToServer(someArg);
20
20
}
21
21
```
22
22
23
-
Of course you can then go ahead and annotate:
23
+
Звичайно, ви можете продовжити і описати:
24
24
25
25
```ts
26
26
function log(someArg:number) {
27
27
sendDataToServer(someArg);
28
28
}
29
29
```
30
30
31
-
And if you truly want *zero safety* you can mark it *explicitly* as`any`:
31
+
І якщо ви справді бажаєте *нульової безпеки*, ви можете позначити його *явно* як`any`:
Copy file name to clipboardExpand all lines: docs/options/strictNullChecks.md
+15-15
Original file line number
Diff line number
Diff line change
@@ -1,23 +1,23 @@
1
1
# `strictNullChecks`
2
2
3
-
By default`null`and`undefined`are assignable to all types in TypeScript e.g.
3
+
За замовчуванням`null`і`undefined`можна призначити всім типам у TypeScript, наприклад,
4
4
5
5
```ts
6
6
let foo:number=123;
7
7
foo=null; // Okay
8
8
foo=undefined; // Okay
9
9
```
10
10
11
-
This is modelled after how a lot of people write JavaScript. However, like all things, TypeScript allows you to be *explicit* about what*can and cannot be*assigned a`null`or`undefined`.
11
+
Це змодельовано за тим, як багато людей пишуть JavaScript. Однак, як і всі інші речі, TypeScript дозволяє *явно* визначити, чому*can and cannot be*присвоїти значення`null`або`undefined`.
12
12
13
-
In strict null checking mode,`null`and`undefined`are different:
13
+
У режимі суворої перевірки null`null`і`undefined`відрізняються:
14
14
15
15
```ts
16
16
let foo =undefined;
17
17
foo=null; // NOT Okay
18
18
```
19
19
20
-
Let's say we have a`Member` interface:
20
+
Скажімо, у нас є інтерфейс`Member`:
21
21
22
22
```ts
23
23
interfaceMember {
@@ -26,29 +26,29 @@ interface Member {
26
26
}
27
27
```
28
28
29
-
Not every`Member`will provide their age, so`age`is an optional property, meaning the value of `age`may or may not be`undefined`.
29
+
Не кожен`Member`вказує свій вік, тому`age`є необов'язковою властивістю, тобто значення `age`може бути або не бути`undefined`.
30
30
31
-
`undefined`is the root of all evil. It often leads to runtime errors. It is easy to write code that will throw `Error`at runtime:
31
+
`undefined`- це корінь усього зла. Це часто призводить до помилок виконання. Легко написати код, який видаватиме `Error`під час виконання:
32
32
33
33
```ts
34
34
getMember()
35
35
.then(member: Member=> {
36
-
const stringifyAge =member.age.toString() //Cannot read property 'toString' of undefined
36
+
const stringifyAge =member.age.toString() //не можу примінити 'toString' к undefined
37
37
})
38
38
```
39
39
40
-
But in strict null checking mode, this error will be caught at compile time:
40
+
Але в режимі суворої перевірки null ця помилка буде виявлена під час компіляції:
41
41
42
42
```ts
43
43
getMember()
44
44
.then(member: Member=> {
45
-
const stringifyAge =member.age.toString() //Object is possibly 'undefined'
45
+
const stringifyAge =member.age.toString() //Об'єкт можливо 'undefined'
46
46
})
47
47
```
48
48
49
49
## Non-Null Assertion Operator
50
50
51
-
A new `!`post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. For example:
51
+
Новий оператор постфіксованого виразу `!`може бути використаний для підтвердження того, що його операнд не є нульовим і не визначеним у контекстах, де перевірка типу не може зробити висновок про цей факт. Наприклад:
52
52
53
53
```ts
54
54
// Compiled with --strictNullChecks
@@ -63,11 +63,11 @@ function processEntity(e?: Entity) {
63
63
}
64
64
```
65
65
66
-
> Note that it is just an assertion, and just like type assertions *you are responsible* for making sure the value is not null. A non-null assertion is essentially you telling the compiler "I know it's not null so let me use it as though it's not null".
66
+
> Зауважте, що це лише твердження, і, як і твердження типу *ви відповідаєте* за те, щоб значення не було нульовим. Ненульове твердження, по суті, означає, що ви говорите компілятору: «Я знаю, що це не нуль, тому дозвольте мені використовувати його так, ніби воно не нульове».
67
67
68
68
### Definite Assignment Assertion Operator
69
69
70
-
TypeScript will also complain about properties in classes not being initialized e.g.:
70
+
TypeScript також скаржиться на неініціалізацію властивостей у класах, наприклад:
71
71
72
72
```ts
73
73
classC {
@@ -80,7 +80,7 @@ class C {
80
80
}
81
81
```
82
82
83
-
You can use the definite assignment assertion postfixed to the property name to tell TypeScript that you are initializing it somewhere other than the constructor e.g.
83
+
Ви можете використовувати твердження визначеного призначення, додане до назви властивості, щоб повідомити TypeScript, що ви ініціалізуєте його десь, крім конструктора, наприклад.
84
84
85
85
```ts
86
86
classC {
@@ -98,7 +98,7 @@ class C {
98
98
}
99
99
```
100
100
101
-
You can also use this assertion with simple variable declarations e.g.:
101
+
Ви також можете використовувати це твердження з простими оголошеннями змінних, наприклад:
102
102
103
103
```ts
104
104
let a:number[]; // No assertion
@@ -115,4 +115,4 @@ function initialize() {
115
115
}
116
116
```
117
117
118
-
> Like all assertions, you are telling the compiler to trust you. The compiler will not complain even if the code doesn't actually always assign the property.
118
+
> Як і всі твердження, ви говорите компілятору довіряти вам. Компілятор не скаржиться, навіть якщо код насправді не завжди призначає властивість.
The compilation context is basically just a fancy term for grouping of the files that TypeScript will parse and analyze to determine what is valid and what isn't. Along with the information about which files, the compilation context contains information about *which compiler options* are in use. A great way to define this logical grouping (we also like to use the term *project*) is using a `tsconfig.json` file.
2
+
Контекст компіляції — це, по суті, просто модний термін для групування файлів, які TypeScript читати та аналізуватиме, щоб визначити, що є дійсним, а що ні. Разом з інформацією про те, які є файли, контекст компіляції містить інформацію про *які параметри компілятора* використовуються. Чудовий спосіб визначити це логічне групування (ми також любимо використовувати термін *project*) — це використовувати файл `tsconfig.json`.
There are two declaration spaces in TypeScript: the *variable*declaration space and the *type* declaration space. These concepts are explored below.
3
+
У TypeScript є два простори оголошень: простір оголошення *variable*і простір оголошення *type*. Ці поняття досліджуються нижче.
4
4
5
5
### Type Declaration Space
6
-
The type declaration space contains stuff that can be used as a type annotation. E.g. the following are a few type declarations:
6
+
Простір оголошення типу містить матеріал, який можна використовувати як анотацію типу. Наприклад нижче наведено кілька декларацій типів:
7
7
8
8
```ts
9
9
classFoo {};
10
10
interfaceBar {};
11
11
typeBas= {};
12
12
```
13
-
This means that you can use`Foo`, `Bar`, `Bas`, etc. as a type annotation. E.g.:
13
+
Це означає, що ви можете використовувати`Foo`, `Bar`, `Bas` як анотацію типу. Наприклад:
14
14
15
15
```ts
16
16
var foo:Foo;
17
17
var bar:Bar;
18
18
var bas:Bas;
19
19
```
20
20
21
-
Notice that even though you have `interface Bar`, *you can't use it as a variable* because it doesn't contribute to the *variable declaration space*. This is shown below:
21
+
Зауважте, що навіть якщо у вас є `інтерфейс`, *ви не можете використовувати її як змінну*, оскільки вона не сприяє *простору оголошення змінних*. Це показано нижче:
22
22
23
23
```ts
24
24
interfaceBar {};
25
25
var bar =Bar; // ERROR: "cannot find name 'Bar'"
26
26
```
27
27
28
-
The reason why it says `cannot find name` is because the name `Bar`*is not defined* in the *variable* declaration space. That brings us to the next topic "Variable Declaration Space".
28
+
Причина, чому він каже `не вдається знайти ім’я`, полягає в тому, що ім’я `Bar`*не визначено* у *просторі оголошення змінної*. Це підводить нас до наступної теми «Простір оголошення змінних».
29
29
30
30
### Variable Declaration Space
31
-
The variable declaration space contains stuff that you can use as a variable. We saw that having`class Foo`contributes a type `Foo`to the *type* declaration space. Guess what? It also contributes a *variable*`Foo`to the *variable* declaration space as shown below:
31
+
Простір оголошення змінної містить матеріал, який можна використовувати як змінну. Ми побачили, що наявність`class Foo`вносить тип `Foo`в простір оголошення *type*. Вгадай що? Він також додає *змінну*`Foo`до простору оголошення *змінної*, як показано нижче:
32
32
33
33
```ts
34
34
classFoo {};
35
35
var someVar =Foo;
36
36
var someOtherVar =123;
37
37
```
38
-
This is great as sometimes you want to pass classes around as variables. Remember that:
38
+
Це чудово, оскільки іноді ви хочете передати класи як змінні. Пам'ятайте, що:
39
39
40
-
*we couldn't use something like an `interface` that is *only* in the *type*declaration space as a variable.
40
+
*ми не могли використовувати щось на зразок `інтерфейсу`, який є *тільки* у просторі оголошення *type*як змінну.
41
41
42
-
Similarly something that you declare with `var`, is *only* in the *variable*declaration space and cannot be used as a type annotation:
42
+
Подібним чином те, що ви оголошуєте за допомогою `var`, знаходиться *тільки* в просторі оголошення *variable*і не може використовуватися як анотація типу:
43
43
44
44
```ts
45
45
var foo =123;
46
46
var bar:foo; // ERROR: "cannot find name 'foo'"
47
47
```
48
-
The reason why it says `cannot find name` is because the name `foo`*is not defined* in the *type* declaration space.
48
+
Причина, чому написано `не вдається знайти ім’я`, полягає в тому, що ім’я `foo`*не визначено* у просторі оголошення *type*.
0 commit comments