Skip to content

Commit 7c91578

Browse files
authored
Merge pull request #392 from apify/switching-to-typescript
Create switching to Typescript section
2 parents f491c39 + e51bad8 commit 7c91578

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+1764
-6
lines changed

content/academy/concepts.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Concepts
33
description: Learn about some common yet tricky concepts and terms that are used frequently within the academy, as well as in the world of scraper development.
4-
menuWeight: 8
4+
menuWeight: 9
55
category: glossary
66
paths:
77
- concepts

content/academy/glossary.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
---
22
title: Why a glossary?
33
description: Browse important web scraping concepts, tools and topics in succinct articles explaining common web development terms in a web scraping and automation context.
4-
menuWeight: 7
4+
menuWeight: 8
55
category: glossary
66
paths:
77
- glossary

content/academy/homepage_content.json

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,8 @@
55
"link": "academy/web-scraping-for-beginners",
66
"description": "Learn how to develop web scrapers on your own computer with open-source tools. This web scraping course teaches you all the basics a scraper developer needs to know.",
77
"imageUrl": "/img/use-cases/product-development/intro.svg"
8-
}, {
8+
},
9+
{
910
"title": "Apify platform",
1011
"link": "academy/apify-platform",
1112
"description": "The Apify platform is the best place to run your scrapers and automations in the cloud. Learn what an actor is, how to turn your program into an actor, and how to deploy it.",
@@ -18,12 +19,14 @@
1819
"link": "academy/api-scraping",
1920
"description": "Learn all about how the professionals scrape various types of APIs with various configurations, parameters, and requirements.",
2021
"imageUrl": "/img/actors/actors-01.svg"
21-
}, {
22+
},
23+
{
2224
"title": "Anti-scraping protections",
2325
"link": "academy/anti-scraping",
2426
"description": "Understand the various anti-scraping measures different sites use to prevent bots from accessing them, and how to appear more human to fix these issues.",
2527
"imageUrl": "/img/proxy/proxy-01.svg"
26-
}, {
28+
},
29+
{
2730
"title": "Expert scraping with Apify",
2831
"link": "academy/expert-scraping-with-apify",
2932
"description": "After learning the basics of actors, learn to develop pro-level scrapers on the Apify platform with this advanced course.",
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
title: Switching to TypeScript
3+
description: In this course, learn what TypeScript is, why you should use it instead of vanilla JavaScript, and how to start using it in your own projects.
4+
menuWeight: 7
5+
category: courses
6+
paths:
7+
- switching-to-typescript
8+
---
9+
10+
# [](#switching-to-typescript) Switching to TypeScript
11+
12+
As the world of JavaScript moves forward, [TypeScript](https://www.typescriptlang.org/) continues to become more popular. More companies than ever before are using TypeScript in their codebases, and are heavily preferring it over vanilla JavaScript. But why? What is TypeScript, and why is is so great for developers?
13+
14+
![TypeScript logo]({{@asset switching_to_typescript/images/typescript-logo.webp}})
15+
16+
## [](#what-is-typescript) What is TypeScript?
17+
18+
If you're familiar with the fundamentals of any programming language (JavaScript included), then you're familiar with the concept of **types**. String, boolean, array, object, number - these are all types. What TypeScript does is bring [type safety](https://en.wikipedia.org/wiki/Type_safety) to JavaScript, which is normally a [dynamically typed](https://developer.mozilla.org/en-US/docs/Glossary/Dynamic_typing) and [interpreted](https://www.geeksforgeeks.org/difference-between-compiled-and-interpreted-language/) programming language. This means that if you have declare a variable like this: `const foo = 'bar'`, then later try to access the non-existent property of `foo.baz`, you'll only know about the error once it happens during runtime.
19+
20+
To sum everything said up above, here's a code example written in JavaScript that has a couple of problems with it:
21+
22+
```JavaScript
23+
const john = {
24+
name: 'john',
25+
job: 'web developer',
26+
};
27+
28+
const bob = {
29+
name: 'bob',
30+
job: 'data analyst',
31+
age: '27',
32+
};
33+
34+
const addAges = (num1, num2) => num1 + num2;
35+
36+
console.log(addAges(bob.age, john.age));
37+
```
38+
39+
This code doesn't actually throw an error, but it does output `27undefined`. That's not good. The first issue is that `john.age` is **undefined**, and the second issue is that `bob.age` is a string and must be converted to a number to work properly in the `addAges` function. Despite these two significant mistakes, JavaScript doesn't tell us at all about them and lets the code run with bugs.
40+
41+
With TypeScript, these types of issues stick out like a sore thumb, and depending on your configurations, the [compiler](https://www.techtarget.com/whatis/definition/compiler#:~:text=A%20compiler%20is%20a%20special,as%20Java%20or%20C%2B%2B.) will refuse to compile it until they have been fixed.
42+
43+
![]({{@asset switching_to_typescript/images/typescript-error.webp}})
44+
45+
This means that when using TS (a popular acronym for "TypeScript") on a large project, you'll run into much less runtime errors and catch the majority of them during the development process.
46+
47+
## [](#advantages-of-typescript) What are the advantages of using TypeScript?
48+
49+
1. The ability to **optionally** [statically type](https://developer.mozilla.org/en-US/docs/Glossary/Static_typing) your variables and functions.
50+
2. [Type Inference](https://www.typescriptlang.org/docs/handbook/type-inference.html), which provides you the benefits of using types, but without having to actually statically type anything. For example, if you create a variable like this: `let num = 5`, TypeScript will automatically infer that `num` is of a **number** type.
51+
3. Access to the newest features in JavaScript before they are officially supported everywhere.
52+
4. Fantastic support with [IntelliSense](https://en.wikipedia.org/wiki/Intelligent_code_completion) and epic autocomplete when writing functions, accessing object properties, etc. Most modern IDEs have TypeScript support.
53+
5. Access to exclusive TypeScript features such as [Enums](https://www.typescriptlang.org/docs/handbook/enums.html).
54+
<!-- and [Decorators](https://www.typescriptlang.org/docs/handbook/decorators.html). -->
55+
56+
## [](#how-different-is-it) How different is TypeScript from JavaScript?
57+
58+
Think of it this way: Javascript **IS** Typescript, but TypeScript isn't JavaScript. All JavaScript code is valid TypeScript code, which means that you can pretty much turn any **.js** file into a **.ts** file and it'll still work just the same after being compiled. It also means that to learn TypeScript, you aren't going to have to learn a whole new programming language if you already know JavaScript.
59+
60+
So, what are the differences? Well, there's really just one: TypeScript files cannot be run directly. They must first be compiled into regular JavaScript.
61+
62+
## [](#next) Ready to get started?
63+
64+
Now that you're familiar with what TypeScript is and aware of its many advantages, let's [get started]({{@link switching_to_typescript/installation.md}}) in our TS journey by installing the TypeScript compiler (super easy) and writing our first line of code in a **.ts** file.
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
---
2+
title: Enums
3+
description: Learn how to easily define, use, and manage constant values using this epic feature called "enums" that TypeScript brings to the table.
4+
menuWeight: 7.4
5+
paths:
6+
- switching-to-typescript/enums
7+
---
8+
9+
# [](#enums) Enums!
10+
11+
Enums are an awesome feature offered by TypeScript that can be used to create automatically enumerated global constant identifiers that can also be used as custom types. We've dedicated an entire lesson to enums because they're a new feature brought into JavaScript by TypeScript, and because they can be massively useful in certain projects.
12+
13+
## [](#lets-talk-about-constants) Let's talk about constants
14+
15+
If you've followed along with any of the more advanced courses in the Apify academy, or at least read the [Best practices]({{@link web_scraping_for_beginners/best_practices.md}}) lesson in the **Web scraping for beginners** course, you'll definitely be familiar with the idea of constant variables. In a nutshell, we create constant variables for values that will never change, and will likely used in multiple places. The naming convention for constants is **ALL_CAPS_AND_UNDERSCORED**.
16+
17+
Here's an object of constant values that we've prepared for use within our project.
18+
19+
```TypeScript
20+
const fileExtensions = {
21+
JAVASCRIPT: '.js',
22+
TYPESCRIPT: '.ts',
23+
RUST: '.rs',
24+
PYTHON: '.py',
25+
};
26+
```
27+
28+
No problem, this will totally work; however, the issue is that TypeScript doesn't know what these values are, but it infers them to just be strings. We can solve this by adding a type annotation with a custom type definition:
29+
30+
```TypeScript
31+
// DON'T DO THIS! Use enums instead!
32+
33+
// Since TypeScript infers these values to be just strings,
34+
// we have to create a type definition telling it that these
35+
// properties hold super specific strings.
36+
const fileExtensions: {
37+
JAVASCRIPT: '.js';
38+
TYPESCRIPT: '.ts';
39+
RUST: '.rs';
40+
PYTHON: '.py';
41+
// Define the object's values
42+
} = {
43+
JAVASCRIPT: '.js',
44+
TYPESCRIPT: '.ts',
45+
RUST: '.rs',
46+
PYTHON: '.py',
47+
};
48+
```
49+
50+
> Using an actual concrete value such as `'.js'` or `24` or something else instead of a type name is called a [literal type](https://www.typescriptlang.org/docs/handbook/literal-types.html).
51+
52+
And now we'll create a variable with a hacky custom type that points to the values in the `fileExtensions` object:
53+
54+
![TypeScript autofilling the values of the fileExtensions object]({{@asset switching_to_typescript/images/constant-autofill.webp}})
55+
56+
Because of the custom type definition for `fileExtensions` and the type annotation used for the `values` variable, we are getting some autofill for the variable, and the variable can only be set to values within the `fileExtensions` object. Though this implementation might be useful somewhere, it kind of sucks for a few reasons. We had to write our `fileExtensions` property twice (once for TypeScript, and another time to actually initialize the object), and had to use a weird type definition for `values`.
57+
58+
Don't worry, there's a better way! Enter **enums**.
59+
60+
## [](#creating-enums) Creating enums
61+
62+
The [`enum`](https://www.typescriptlang.org/docs/handbook/enums.html) keyword is a new keyword brought to us by TypeScript that allows us the same functionality we implemented in the above section, plus more. To create one, simply use the keyword followed by the name you'd like to use (the naming convention is generally **CapitalizeEachFirstLetterAndSingular**).
63+
64+
```TypeScript
65+
enum FileExtension {
66+
// Use an "=" sign instead of a ":"
67+
JAVASCRIPT = '.js',
68+
TYPESCRIPT = '.ts',
69+
RUST = '.rs',
70+
PYTHON = '.py',
71+
}
72+
```
73+
74+
## [](#using-enums) Using enums
75+
76+
Using enums is straightforward. Simply use dot notation as you normally would with a regular object.
77+
78+
```TypeScript
79+
enum FileExtension {
80+
JAVASCRIPT = '.js',
81+
TYPESCRIPT = '.ts',
82+
RUST = '.rs',
83+
PYTHON = '.py',
84+
}
85+
86+
const value = FileExtension.JAVASCRIPT;
87+
88+
console.log(value) // => ".js"
89+
```
90+
91+
## [](#using-enums-as-types) Using enums as types
92+
93+
The nice thing about enums is that they can be used directly in type annotations as somewhat of a custom type. Observe this function:
94+
95+
```TypeScript
96+
const createFileName = (name: string, extension: string) => {
97+
return name + extension;
98+
};
99+
```
100+
101+
We can restrict `extension` so that it can only be a value in the enum by replacing `extension: string` with `extension: FileExtension`:
102+
103+
```Typescript
104+
enum FileExtension {
105+
JAVASCRIPT = '.js',
106+
TYPESCRIPT = '.ts',
107+
RUST = '.rs',
108+
PYTHON = '.py',
109+
}
110+
111+
const createFileName = (name: string, extension: FileExtension) => {
112+
return name + extension;
113+
};
114+
115+
// Call the function and use the enum to populate the second parameter
116+
const fileName = createFileName('hello', FileExtension.TYPESCRIPT);
117+
118+
console.log(fileName);
119+
```
120+
121+
We don't get autocomplete, but the `extension` parameter is now restricted to the values defined in the `FileExtension` enum.
122+
123+
## [](#next) Next up
124+
125+
The `enum` keyword is just the tip of the iceberg of the exclusive features TypeScript has to offer. Let's now [learn about]({{@link switching_to_typescript/type_aliases.md}}) type aliases (custom types!) with the `type` keyword.
80.7 KB
Loading
Binary file not shown.
8.89 KB
Loading
Binary file not shown.
52 KB
Loading

0 commit comments

Comments
 (0)