Skip to content

Commit 9b241a6

Browse files
committed
Initial commit
0 parents  commit 9b241a6

File tree

33 files changed

+3575
-0
lines changed

33 files changed

+3575
-0
lines changed

.DS_Store

6 KB
Binary file not shown.

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules/

README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Typescript from Zero
2+
3+
This repository serves as an interactive guide to Typescript.
4+
It contains written guides in the form of README.md files, as well as code examples in the form of `.ts` files.
5+
6+
## Pre-requisites
7+
8+
This course assumes that you have:
9+
10+
- Proficiency with Javascript (or minimally any other language)
11+
12+
Good to have:
13+
14+
- Some experience with Typescript
15+
16+
## Setup
17+
18+
```sh
19+
npm install # Install ESLint and Typescript for type-checking in hands-on exercises.
20+
```
21+
22+
## What this course is
23+
24+
- A guide to Typescript syntax and best practices when using Typescript in your codebase
25+
26+
## What this course is not
27+
28+
- A guide to setting up Typescript in your project
29+
- A Javascript tutorial
30+
31+
## Table of Contents
32+
33+
- TODO

chapters/.DS_Store

6 KB
Binary file not shown.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Setting up your environment
2+
3+
## IDE
4+
5+
We will be using [Visual Studio Code](https://code.visualstudio.com/) with the following extensions:
6+
7+
- [Twoslash Query Comments](https://marketplace.visualstudio.com/items?itemName=Orta.vscode-twoslash-queries) - To show inline type previews
8+
- [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) - To show linting errors
9+
- [Markdown Preview Enhanced](https://marketplace.visualstudio.com/items?itemName=shd101wyy.markdown-preview-enhanced) - To preview markdown files
10+
11+
## Project setup
12+
13+
``` sh
14+
npm install
15+
16+
```

chapters/1-basics/.DS_Store

10 KB
Binary file not shown.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Introduction to Typescript
2+
3+
- Typescript is a typed superset of Javascript.
4+
- It adds additional syntax to Javascript to support types.
5+
6+
## Benefits
7+
8+
- Catch bugs in compile time (i.e. you can catch bugs before running your code).
9+
- Better code completion.
10+
- Better understandability of code
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
# Introduction to type annotations
2+
3+
In TypeScript, you can specify the type of a variable, function, or class by adding *type annotations*.
4+
5+
This helps you catch bugs in your code before you run it, and makes your code more readable and maintainable.
6+
7+
To appreciate the benefits of having types, let's first look at a problem with Javascript.
8+
9+
## The problem with Javascript
10+
11+
Here, we have a Javascript function `add`, which takes in `a` and `b` as parameters, and returns the sum of `a` and `b`. Pretty straightforward.
12+
13+
```ts
14+
// add.js (Javascript)
15+
function add(a, b) {
16+
return a + b;
17+
}
18+
```
19+
20+
21+
We know that `a` and `b` should be numbers because we are adding them together. However, our IDE (and whatever we are running JavaScript on) doesn't know that.
22+
23+
In fact, we can pass in any value to `add` and it will still run.
24+
25+
```js
26+
// add.js (Javascript)
27+
function add(a, b) {
28+
return a + b;
29+
}
30+
31+
console.log(add(1, 2)) // 3; Runs as expected
32+
console.log(add("Hello", "World")) // Should not run, but it does
33+
console.log(add({}, [])) // Should not run, but it does
34+
```
35+
36+
TypeScript allows us to catch these logical errors before we even run our code.
37+
38+
## Converting to TypeScript
39+
40+
Firstly, we have to rename our file from `add.js` to `add.ts`. This tells TypeScript that this file is a TypeScript file.
41+
> Note: For frontend developers using React, you will be converting your component from `MyComponent.js` to the JSX-enabled `MyComponent.tsx` instead.
42+
43+
Immediately, we will get the following error from TypeScript:
44+
45+
```ts
46+
// add.ts
47+
function add(a, b) {
48+
// ^ Error: Parameter 'a' implicitly has an 'any' type.
49+
return a + b;
50+
}
51+
```
52+
53+
This error is telling us that TypeScript doesn't know the type of `a`. We can fix this by adding a type annotation to `a` (and `b`).
54+
55+
> Side note: This error will only be shown if you have `noImplicitAny` set to true in your `tsconfig.json` file. In our case, we have `strict` set to true, which enables `noImplicitAny`. In general, you want `strict` mode to be true as this enables all strict type checking options, which will help you catch more bugs in your code.
56+
57+
## Annotating variables and parameters
58+
59+
We will obtain the following code after adding type annotations to `a` and `b`:
60+
61+
```ts
62+
// add.ts (revised)
63+
64+
// Note: we added type annotations to a and b
65+
function add(a: number, b: number): number {
66+
// ^^^^^^ ^^^^^^ . ^^^^^^
67+
return a + b;
68+
}
69+
```
70+
71+
In Typescript, type annotations are done by adding the type after the variable name, separated by a colon `:`. In this case, we are specifying that `a` and `b` are of type `number`.
72+
73+
Here are more examples of type annotations:
74+
75+
```ts
76+
// ORIGINAL: index.js (Javascript)
77+
const isActive = true
78+
const message = "Hello, World!"
79+
const age = 25
80+
81+
function greet(name) {
82+
return `Hello, ${name}!`
83+
}
84+
85+
///////////////////////////////////////////
86+
// ANNOTATED: index.ts (Typescript)
87+
const isActive: boolean = true
88+
const message: string = "Hello, World!"
89+
const age: number = 25
90+
91+
// Greet is a function that takes in a string and returns a string
92+
function greet(name: string): string {
93+
return `Hello, ${name}!`
94+
}
95+
```
96+
97+
## Annotating return types
98+
99+
As you can see from the previous examples, we can also annotate the return type of a function. This makes TypeScript check that the function returns the correct type.
100+
101+
```ts
102+
// Returning wrong type
103+
function getAge(): number {
104+
return "25" // Error: Type 'string' is not assignable to type 'number'
105+
}
106+
107+
// Missing return value
108+
function getAge(): number {
109+
// Error: A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value.
110+
}
111+
112+
// Returning correct type
113+
function getAge(): number {
114+
return 25 // No error
115+
}
116+
```
117+
118+
## Summary
119+
120+
To summarize, here are the following ways to add type annotations.
121+
122+
```ts
123+
// Replace <type> with the type you want to specify
124+
const a: <type> = ...
125+
126+
function myFunction(param1: <type>, param2: <type>): <type> {
127+
128+
}
129+
130+
const myArrowFunction = (param1: <type>, param2: <type>): <type> => {
131+
132+
}
133+
```
134+
135+
Here are some common basic types you can use:
136+
137+
- `number`
138+
- `string`
139+
- `boolean`
140+
- `null`
141+
- `undefined`
142+
143+
## Exercise 1.1
144+
145+
Try adding some type annotations yourself.
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// EXERCISE 1.1: Add/correct type annotations to all the variable
2+
// and functions below.
3+
4+
const age: number = 25;
5+
const message: string = "Hello, world!";
6+
const isTrue: boolean = true;
7+
8+
function add(a: number, b: number) {
9+
return a + b;
10+
}
11+
12+
function sayHello(name: string) {
13+
return `Hello, ${name}!`;
14+
}
15+
16+
function isEven(n: number) {
17+
return n % 2 === 0;
18+
}
19+
20+
function getAge(): number {
21+
return 25;
22+
}
23+
24+
// ignore the line below
25+
export {};
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// function getUserGreeting(name: string, age: number) {
2+
// const isUserOld = age > 60;
3+
// const isNameCapitalized = name[0] === name[0].toUpperCase();
4+
// const isAgeEven = age % 2 === 0;
5+
// const peopleCount = 25;
6+
7+
// return 25;
8+
// }
9+
10+
// function main() {
11+
// const message = getUserGreeting("John", 25);
12+
// const firstThreeChars = message.substring(0, 3);
13+
// }
14+
function getPerson() {
15+
return ["Alice", 25];
16+
}
17+
18+
const [name, age] = getPerson();
19+
20+
// Don't change the code below this line
21+
export {};
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Classes
2+
3+
Classes are a way to implement object-oriented programming in Javascript. They are automatically a type in TypeScript.
4+
5+
```ts
6+
class User {
7+
constructor(public name: string, public age: number) {}
8+
}
9+
10+
const user = new User("Alice", 25);
11+
// ^ user: User
12+
```
13+
14+
You may use `instanceof` to check if an object is an instance of a class:
15+
16+
```ts
17+
18+
function printDate(date: Date | string) {
19+
if (date instanceof Date) {
20+
console.log(date.toISOString());
21+
// ^ date: Date
22+
return;
23+
}
24+
25+
console.log(new Date(date).toISOString());
26+
}
27+
```

0 commit comments

Comments
 (0)