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
Copy file name to clipboardExpand all lines: module8-typescript/r1-introduction-to-typescript/README.md
+6-6Lines changed: 6 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -29,7 +29,7 @@ console.log(user.name)
29
29
30
30
Actually, TypeScript won't even allow you to run this code: you'll get an error.
31
31
32
-
```bash
32
+
```
33
33
Property 'name' does not exist on type '{ firstName: string; lastName: string; role: string; }'.
34
34
```
35
35
@@ -89,7 +89,7 @@ Generally speaking, it is best not to form any kind of unshakable opinions about
89
89
90
90
We've learned quite a bit about TypeScript and why it makes JavaScript even better. Let's understand this in action with frontend and backend code. TypeScript is compatible with most modern frontend frameworks like React or Next.js. If you're familiar with JSX in React, to use TypeScript you would create a `.tsx` file instead. Let's look at an example of a `Header.tsx` file.
91
91
92
-
```js
92
+
```tsx
93
93
exportinterfaceProps {
94
94
title:string
95
95
color?:string
@@ -109,7 +109,7 @@ Here we have created a Header component that takes in two props `title` and `col
109
109
110
110
So now when we want to have a Header component on a page:
111
111
112
-
```js
112
+
```tsx
113
113
<Header />
114
114
<Headertitle='Hello World' />
115
115
<Headertitle='Hello World'color='red' />
@@ -119,10 +119,10 @@ The first case will give us an error within our IDE stating that the prop title
119
119
120
120
TypeScript is also very compatible on the backend, you can have `.ts` files in your Node Express projects or use a backend framework like NestJS which has TypeScript incorporated. We will learn more about this framework in an upcoming lesson, let's take a look at another TypeScript example useful for backend.
Copy file name to clipboardExpand all lines: module8-typescript/r1.1-everyday-types/README.md
+27-27Lines changed: 27 additions & 27 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -11,15 +11,15 @@ We'll start by reviewing the most basic and common types you might encounter whe
11
11
12
12
When you declare a variable using `const`, `var`, or `let`, you can optionally add a type annotation to explicitly specify the type of the variable:
13
13
14
-
```typescript
14
+
```ts
15
15
let myName:string="Alice";
16
16
```
17
17
18
18
TypeScript doesn't use "types on the left"-style declarations like `int x = 0`; Type annotations will always go after the thing being typed.
19
19
20
20
In most cases, though, this isn’t needed. Wherever possible, TypeScript tries to automatically infer the types in your code. For example, the type of a variable is inferred based on the type of its initializer:
21
21
22
-
```typescript
22
+
```ts
23
23
// No type annotation needed -- 'myName' inferred as type 'string'
24
24
let myName ="Alice";
25
25
```
@@ -28,7 +28,7 @@ let myName = "Alice";
28
28
29
29
JavaScript has three primitive types -- `string`, `number`, `boolean` -- and they are present in TypeScript as well. You can declare them just as you would in JavaScript. However, in TypeScript, you may _optionally_ add a type. As mentioned previously, in most cases TypeScript can infer the type correctly.
What does it mean when TypeScript is type-safe? Let's try adding together a number and a string in both JavaScript and TypeScript:
46
46
47
-
```typescript
47
+
```ts
48
48
// JavaScript: prints "1foo"
49
49
console.log(1+"foo");
50
50
@@ -62,7 +62,7 @@ We'll go through a few examples.
62
62
63
63
TypeScript will infer the type of an array if it is declared with some value initially. For example, we have an array of numbers below; TypeScript is smart enough to figure out that `ids` has the type `number[]`.
64
64
65
-
```typescript
65
+
```ts
66
66
const ids = [1, 2, 3];
67
67
ids.push("somestring");
68
68
```
@@ -77,7 +77,7 @@ Argument of type 'string' is not assignable to parameter of type 'number'.
77
77
78
78
If there is no initial value, TypeScript is, unfortunately, not smart enough to figure out the type of an array. For example:
79
79
80
-
```typescript
80
+
```ts
81
81
// No type is declared on the array. TypeScript doesn't know
82
82
// what type the members are. This code passes, and anything
83
83
// can be pushed into the array (not very helpful for type safety).
@@ -91,7 +91,7 @@ TypeScript believes that the members of the array can be any type (formally: typ
91
91
92
92
If you plan on declaring an empty array, this is an instance where you would want to explicitly specify the type in order to receive type-safety:
93
93
94
-
```typescript
94
+
```ts
95
95
// This will give an error if you try to push a string to the array this time.
96
96
const ids:number[] = [];
97
97
ids.push(5);
@@ -103,14 +103,14 @@ The `number[]` indicates that this will be an array of numbers. Similarly, you c
103
103
104
104
TypeScript also has a special type, `any`, that you can use whenever you don't want a particular value to cause type-checking errors. It is useful when you don't want to write out a long type just to convince TypeScript that a particular line of code is okay.
105
105
106
-
```typescript
106
+
```ts
107
107
let x:any="Hello";
108
108
let arr:any[] = [1, true, "Hello"];
109
109
```
110
110
111
111
When a value is of type `any`, you can access any properties of it (which will, in turn, be of type `any`), call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal.
112
112
113
-
```typescript
113
+
```ts
114
114
let obj:any= { x: 0 };
115
115
// None of the following lines of code will throw compiler errors.
116
116
// Using `any` disables all further type checking, and it is assumed
@@ -128,7 +128,7 @@ When the keyword `any` is used, TypeScript no longer performs type checking, sin
128
128
129
129
Here is an example of typing something as `any`, demonstrating how we can start introducing errors in our code that were previously prevented:
130
130
131
-
```typescript
131
+
```ts
132
132
const a:any= [1, 2, 3, 4, 5];
133
133
const invalidAddition =a+5; // Adding a list to a number?
134
134
const functionDoesntExist =a.someInvalidFunction(); // This also compiles!
@@ -140,7 +140,7 @@ Some valid usages of `any` might be: facilitating code migration from JavaScript
140
140
141
141
Sometimes you may have an array whose elements are of different types. This is usually not encouraged, but it is possible. TypeScript allows type definitions for mixed arrays or tuples. You could even have an array of tuples.
142
142
143
-
```typescript
143
+
```ts
144
144
// Tuple
145
145
let person: [number, string, boolean] = [1, "Alice", true];
146
146
// Tuple Array
@@ -154,7 +154,7 @@ employees = [
154
154
155
155
If you're wondering how is a tuple different from an `any[]`, tuples have a fixed type for each element even if not the same type for all elements. But when you state an array of `any` there could be as many different elements of different types.
156
156
157
-
```typescript
157
+
```ts
158
158
// This tuple would give an error because the third element
159
159
//is expected to be a boolean but is assigned a string
160
160
let employee: [number, string, boolean] = [1, "Alice", "Developer"];
@@ -170,7 +170,7 @@ manager = [false, "Hello"];
170
170
171
171
Functions are the primary means of passing data around in JavaScript. TypeScript allows you to specify the types of both the input and output values of functions. In TypeScript, you can also use both the `function` keyword or arrow functions, but you must add types to the parameters. And where required you can add return type annotations too.
172
172
173
-
```typescript
173
+
```ts
174
174
// Function keyword
175
175
function add(x:number, y:number):number {
176
176
returnx+y;
@@ -186,7 +186,7 @@ Note the addition of three number types: the two parameters `x`, `y`, and the re
186
186
187
187
It should be noted that in TypeScript every parameter is required unless specified by adding a `?` after the parameter. In JavaScript, if a function has three declared parameters, you can choose not to provide them, and they will take the value of `undefined`. This is not the case in TypeScript.
188
188
189
-
```typescript
189
+
```ts
190
190
// Return both the first name and last name if the last name is provided,
191
191
// otherwise return only the first name.
192
192
function makeName(firstName:string, lastName?:string) {
@@ -204,7 +204,7 @@ In the example above, the second parameter, `lastName`, is optional. This is bec
204
204
205
205
Anonymous functions are a little bit different from function declarations. When a function appears in a place where TypeScript can determine how it's going to be called, the parameters of that function are automatically given types.
206
206
207
-
```typescript
207
+
```ts
208
208
// No type annotations here, but TypeScript can spot the bug
209
209
const names = ["Alice", "Bob", "Eve"];
210
210
@@ -225,7 +225,7 @@ We learned how to write types on a function, but it's very common in JavaScript
225
225
226
226
Consider a function that takes another function that operates on numbers (consider this a version of `map`, that, for the sake of example, only works on numbers).
227
227
228
-
```typescript
228
+
```ts
229
229
// Takes a list of numbers and applies a processor function to each number
230
230
function mapNumbers(nums:number[], fn: (x:number):number) {
231
231
returnnums.map(fn);
@@ -238,17 +238,17 @@ Note the syntax here to declare a function type. You must add the parameter name
238
238
239
239
A union type is a type formed from two or more other types, representing values that may be any one of those types. We refer to each of these types as the union's members.
240
240
241
-
```typescript
241
+
```ts
242
242
let id:string|number;
243
243
// This is valid
244
244
id=22;
245
245
// This is also valid
246
246
id="22";
247
247
```
248
248
249
-
It's easy to provide a value matching a union type - simply provide a type matching any of the union's members. If you have a value of a union type, how do you work with it? TypeScript will only allow an operation if it is valid for every member of the union. For example, if you have the union `string | number`, you can`t use methods that are only available on `string`:
249
+
It's easy to provide a value matching a union type - simply provide a type matching any of the union's members. If you have a value of a union type, how do you work with it? TypeScript will only allow an operation if it is valid for every member of the union. For example, if you have the union `string | number`, you can't use methods that are only available on `string`:
@@ -258,7 +258,7 @@ Property 'toUpperCase' does not exist on type 'string | number'.
258
258
259
259
The solution is to narrow the union with code, the same as you would in JavaScript without type annotations. Narrowing occurs when TypeScript can deduce a more specific type for a value based on the structure of the code. For example, TypeScript knows that only a `string` value will have a `typeof` value `"string"`:
260
260
261
-
```typescript
261
+
```ts
262
262
function printId(id:number|string) {
263
263
if (typeofid==="string") {
264
264
// In this branch, id is of type 'string'
@@ -276,7 +276,7 @@ Apart from primitives, the most common sort of type you'll encounter is an objec
276
276
277
277
For example, here's a function that takes a point-like object:
278
278
279
-
```typescript
279
+
```ts
280
280
// The parameter's type annotation is an object type
281
281
function printCoord(pt: { x:number; y:number }) {
282
282
console.log("The coordinate's x value is "+pt.x);
@@ -289,7 +289,7 @@ Here, we annotated the parameter with a type with two properties - `x` and `y` -
289
289
290
290
Object types can also specify that some or all of their properties are optional. To do this, add a `?` after the property name:
291
291
292
-
```typescript
292
+
```ts
293
293
function printName(obj: { first:string; last?:string }) {
In JavaScript, if you access a property that doesn't exist, you'll get the value undefined rather than a runtime error. Because of this, when you read from an optional property, you'll have to check for undefined before using it.
302
302
303
-
```typescript
303
+
```ts
304
304
function printName(obj: { first:string; last?:string }) {
305
305
// Error - might crash if 'obj.last' wasn't provided!
We've been using object types and union types by writing them directly in type annotations. This is convenient, but it's common to want to use the same type more than once and refer to it by a single name. A type alias is exactly that - a name for any type. The syntax for a type alias is:
321
321
322
-
```typescript
322
+
```ts
323
323
typePoint= {
324
324
x:number;
325
325
y:number;
@@ -341,7 +341,7 @@ With `strictNullChecks` off, values that might be `null` or `undefined` can stil
341
341
342
342
With `strictNullChecks` on, when a value is `null` or `undefined`, you will need to test for those values before using methods or properties on that value. Just like checking for `undefined` before using an optional property, we can use narrowing to check for values that might be null:
343
343
344
-
```typescript
344
+
```ts
345
345
function doSomething(x:string|null) {
346
346
if (x===null) {
347
347
// do nothing
@@ -353,7 +353,7 @@ function doSomething(x: string | null) {
353
353
354
354
TypeScript also has a special syntax for removing `null` and `undefined` from a type without doing any explicit checking. Writing `!` after any expression is effectively a type assertion that the value isn't `null` or `undefined`:
355
355
356
-
```typescript
356
+
```ts
357
357
function liveDangerously(x?:number|null) {
358
358
// No error
359
359
console.log(x!.toFixed());
@@ -364,7 +364,7 @@ function liveDangerously(x?: number | null) {
364
364
365
365
Enums are a feature added to JavaScript by TypeScript which allows for describing a value that could be one of a set of possible named constants. Unlike most TypeScript features, this is not a type-level addition to JavaScript but something added to the language and runtime. Because of this, it's a feature that you should know exists, but maybe hold off on using it unless you are sure.
366
366
367
-
```typescript
367
+
```ts
368
368
// Up is initialized with 1
369
369
// All of the following members are auto-incremented from that point on
Copy file name to clipboardExpand all lines: module8-typescript/r1.2-advanced-types/README.md
+8-8Lines changed: 8 additions & 8 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -9,7 +9,7 @@ We have learned quite a bit about Types so far, but when it comes to large-scale
9
9
10
10
An interface declaration is another way to name an object type. Interfaces can be used interchangeably with type aliases and simple object types.
11
11
12
-
```typescript
12
+
```ts
13
13
interfacePoint {
14
14
x:number;
15
15
y:number;
@@ -27,7 +27,7 @@ Like when we used a type alias above, the example works just as if we had used a
27
27
28
28
You can also define properties in an interface to be optional using `?` or non-editable by specifying `readonly`.
29
29
30
-
```typescript
30
+
```ts
31
31
interfaceUserInterface {
32
32
readonly id:number;
33
33
name:string;
@@ -42,7 +42,7 @@ const user1: UserInterface = {
42
42
43
43
Interfaces can be used with functions as well.
44
44
45
-
```typescript
45
+
```ts
46
46
interfaceMathFunc {
47
47
(x:number, y:number):number;
48
48
}
@@ -55,7 +55,7 @@ const sub: MathFunc = (x: number, y: number): number => x - y;
55
55
56
56
TypeScript offers full support for the class keyword introduced in ES2015. As with other JavaScript language features, TypeScript adds type annotations and other syntax features to allow you to express relationships between classes and other types. Just like any other OOP language, classes have members or fields and a constructor function is used to instantiate the objects of this class with initial field values. Classes can also have member functions.
57
57
58
-
```typescript
58
+
```ts
59
59
// Class with constructor
60
60
classPerson {
61
61
id:number;
@@ -77,7 +77,7 @@ alice.greet("Hello");
77
77
78
78
You can use an `implements` clause to check that a class satisfies a particular interface.
79
79
80
-
```typescript
80
+
```ts
81
81
interfacePersonInterface {
82
82
id:number;
83
83
name:string;
@@ -107,7 +107,7 @@ mike.register();
107
107
108
108
Classes may extend from a base class. A derived class has all the properties and methods of its base class, and also defines additional members.
109
109
110
-
```typescript
110
+
```ts
111
111
classEmployeeextendsPerson {
112
112
position:string; // additional member of this subclass
113
113
@@ -139,7 +139,7 @@ We've tried to cover the basics of Classes here. You can read a lot more in deta
139
139
140
140
Generics allow us to create reusable and flexible components which can work over a variety of types rather than a single one. This allows users to consume these components and use their types.
141
141
142
-
```typescript
142
+
```ts
143
143
// Without generics
144
144
function getArray(items:any[]):any[] {
145
145
returnnewArray().concat(items);
@@ -167,7 +167,7 @@ With the introduction of Classes in TypeScript and ES6, there now exist certain
167
167
168
168
A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property, or parameter. Decorators use the form `@expression`, where `expression` must be a function that will be called at runtime with information about the decorated declaration. For example, given the decorator `@sealed` we might write the `sealed` function as follows:
Copy file name to clipboardExpand all lines: module8-typescript/r2-typescript-node-express/README.md
+2-2Lines changed: 2 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -92,7 +92,7 @@ Now if we run `npm run dev` we should see our Express server running in watch mo
92
92
93
93
Now let's add in some meaningful types in our Express server code. We'll use the custom Express types - Application, Request, Response, and NextFunction.
0 commit comments