@@ -10,7 +10,7 @@ JavaScript. We'll examine the benefits of this throughout this module.
10
10
For example, in the following code in TypeScript, notice that the ` user.name `
11
11
field does not exist (only ` user.firstName ` , ` user.lastName ` ).
12
12
13
- ```
13
+ ``` typescript
14
14
const user = {
15
15
firstName: " Angela" ,
16
16
lastName: " Davis" ,
@@ -121,22 +121,203 @@ point of compiler teams). You can read more about some of the tradeoffs between
121
121
JavaScript has three primitive types -- ` string ` , ` number ` , ` boolean ` -- and they are present in TypeScript as
122
122
well.
123
123
124
- Below, let's compare some JavaScript and TypeScript declarations of basic
125
- variables.
124
+ You can declare them just as you would in JavaScript. However, in TypeScript,
125
+ you may * optionally* add a type. In most cases, however, TypeScript can infer
126
+ the type correctly.
126
127
127
- ```
128
- // JavaScript
129
- const graduatingYear = 36;
128
+
129
+ ``` typescript
130
+ // TypeScript infers the type.
131
+ const age = 36 ;
130
132
const isInBootcamp = true ;
131
133
const name = " Foo Bar" ;
134
+
135
+ // However, if you would like, you can explicitly write the types
136
+ // after the variable names. In most cases, this is not necessary,
137
+ // but it may be helpful if you are getting an error message.
138
+ const age: number = 36 ;
139
+ const isInBootcamp: boolean = true ;
140
+ const name: string = " Foo Bar" ;
132
141
```
133
142
134
- Now in TypeScript, when we declare a variable, ;q
143
+ What does it mean when TypeScript is type-safe? Let's try adding together a
144
+ number and a string in both JavaScript and TypeScript:
145
+
146
+ ``` typescript
147
+ // JavaScript: prints "1foo"
148
+ console .log (1 + " foo" );
149
+
150
+ // TypeScript: gives an error
151
+ console .log (1 + " foo" );
152
+ ```
135
153
136
154
137
155
### Arrays
138
156
139
- ### Functinos
157
+ The syntax for arrays in TypeScript is again no different than JavaScript.
158
+ However, typing becomes more important here. To declare an array of some type,
159
+ we use the notation ` string[] ` , ` number[] ` , and so on. You can also use the
160
+ syntax ` Array<string> ` , ` Array<number> ` , and so on. There is no difference. Note
161
+ that this is the syntax for referring to the ** type** of the variable,
162
+
163
+ We'll go through a few examples.
164
+
165
+ #### Inferred array types
166
+ TypeScript will infer the type of an array if it is declared with some value
167
+ initially. For example, we have an array of numbers below; TypeScript is smart
168
+ enough to figure out that ` a ` has type ` number[] ` .
169
+
170
+ ``` typescript
171
+ const a = [1 , 2 , 3 ];
172
+ a .push (" somestring" );
173
+ ```
174
+
175
+ This gives an error, which tells us that we can't push a string to the parameter
176
+ (of the ` push ` function) that expects type ` number ` . TypeScript has inferred
177
+ that this is an array of numbers.
178
+
179
+ ```
180
+ Argument of type 'string' is not assignable to parameter of type 'number'.
181
+ ```
182
+
183
+ #### Limits of inference
184
+ If there is no initial value, TypeScript is, unfortunately, not smart enough to
185
+ figure out the type of an array. For example:
186
+
187
+ ``` typescript
188
+ // No type is declared on the array. TypeScript doesn't know
189
+ // what type the members are. This code passes, and anything
190
+ // can be pushed into the array (not very helpful for type safety).
191
+ const a = [];
192
+ a .push (" somestring" );
193
+ a .push (5 );
194
+ a .push ({})
195
+ ```
196
+
197
+ TypeScript believes that the members of the array can be any type (formally:
198
+ type ` any ` , which will be discussed later).
199
+
200
+ If you plan on declaring an empty array, this is an instance where you would
201
+ want to explicitly specify the type in order to receive type-safety:
202
+
203
+ ``` typescript
204
+ // This will give an error if you try to push a string to the array this time.
205
+ const a: number [] = [];
206
+ a .push (5 );
207
+ ```
208
+
209
+ #### Having arrays with multiple types
210
+ What if you did, for some reason, want to have an array that contains both
211
+ strings and numbers? (Note: this is discouraged, in practice you usually would
212
+ not want to mix the types of members of an array like this).
213
+
214
+ Here, we briefly look at [ union
215
+ types] ( https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html ) .
216
+ A union type is simply a type that could be one of many types. If a variable
217
+ could contain both a string and a number, we use the syntax ` number | string ` .
218
+ The ` | ` can be thought of as similar to a boolean "or" (` || ` ).
219
+
220
+ The following example shows an array that could contain both strings and
221
+ numbers:
222
+
223
+ ``` typescript
224
+ // No errors.
225
+ const a: (number | string )[] = [];
226
+ a .push (" somestring" );
227
+ a .push (5 );
228
+ ```
229
+
230
+ ### Functions
231
+
232
+ #### Writing functions
233
+ In TypeScript, you can also use both the ` function ` keyword or arrow functions,
234
+ but you must add types to the parameters.
235
+
236
+ ``` typescript
237
+ // Function keyword
238
+ function add(x : number , y : number ): number {
239
+ return x + y ;
240
+ }
241
+
242
+ // Arrow function
243
+ const add = (x : number , y : number ): number => {
244
+ return x + y ;
245
+ };
246
+
247
+ ```
248
+
249
+ Note the addition of three number types: the two parameters ` x ` , ` y ` , and the
250
+ return type ` number ` . You may omit the return type sometimes if TypeScript is
251
+ able to infer it, but it's also good practice to keep it in so that readers of
252
+ your functions, such as your teammates, can immediately know at a glance what
253
+ type should be returned from the function.
254
+
255
+ It should be noted that in TypeScript every parameter is required unless
256
+ specified by adding a ` ? ` after the parameter. In JavaScript, if a function has
257
+ three declared parameters, you can choose not to provide them, and they will
258
+ take the value of ` undefined ` . This is not the case in TypeScript.
259
+ In the example below, the second parameter, ` lastName ` , is optional. This is
260
+ because it is written as ` lastName?: string ` . Note that this is equivalent to
261
+ declaring it as ` lastName: string | undefined ` (the question mark is equivalent
262
+ syntax).
263
+
264
+ ``` typescript
265
+ // Return both the first name and last name if the last name is provided,
266
+ // otherwise return only the first name.
267
+ function makeName(firstName : string , lastName ? : string ) {
268
+ if (lastName ) {
269
+ return firstName + " " + lastName ;
270
+ } else {
271
+ return firstName ;
272
+ }
273
+ }
274
+ ```
275
+
276
+ #### Types of function values
277
+ We learned how to write types on a function, but it's very common in JavaScript
278
+ to pass functions as values. For example, using ` map ` , ` reduce ` , or any type of
279
+ callback, a function accepts another function as a parameter. Let's look at ohw
280
+ to write the type of such a function.
140
281
282
+ Consider a function that takes another function that operates on numbers
283
+ (consider this a version of ` map ` , that, for the sake of example, only works on
284
+ numbers).
285
+
286
+ ``` typescript
287
+ // Takes a list of numbers and adds five to every number.
288
+ function mapNumbers(nums : number [], fn : (x : number ) => number ) {
289
+ return nums .map (fn );
290
+ }
291
+ ```
292
+
293
+ Note the syntax here to declare a function type. You must add the parameter
294
+ names, even in the types. The parameter ` fn ` has the type `(x: number) =>
295
+ number` . It takes one parameter ` x` of type ` number` , and it returns a ` number`
296
+ as a result.
141
297
142
298
### Avoiding ` any `
299
+ In TypeScript, there exists a type called ` any ` , which represents any type.
300
+ Beginners of TypeScript are often tempted to use ` any ` type, but it is highly
301
+ discouraged. It is possible in almost all cases to write code without ` any ` . Do not use ` any ` as a
302
+ crutch in order to skip past type errors: doing so is often a sign that
303
+ something else is wrong with the code (and ` any ` is simply being used to ignore
304
+ the fundamental issue).
305
+
306
+ When the keyword ` any ` is used, TypeScript no longer performs typechecking,
307
+ since it has no information about the type. This means that we no longer have
308
+ the benefits of the type-checker.
309
+
310
+ Here is an example of typing something as ` any ` , demonstrating how we can start
311
+ introducing errors in our code that were previously prevented:
312
+
313
+ ```
314
+ const a: any = [1, 2, 3, 4, 5];
315
+ const invalidAddition = a + 5; // Adding a list to a number?
316
+ const functionDoesntExist = a.someInvalidFunction(); // This also compiles!
317
+ ```
318
+
319
+ Some valid usages of ` any ` might be: facilitating migration of code from
320
+ JavaScript to TypeScript, leveraging third-party code without types, working
321
+ with input of completely unknown structure.
322
+
323
+
0 commit comments