Professional Documents
Culture Documents
TypeScript - Crash Course. Concise and Clear TypeScript Tutorial - by Jan Cibulka - Medium
TypeScript - Crash Course. Concise and Clear TypeScript Tutorial - by Jan Cibulka - Medium
Become a member
The main benefit of TypeScript is the ability to use static types. Hence the name
“type-script”.
Statically typed languages (TypeScript, Java, C++, Rust, Go) require that you
explicitly assign types to variables, function parameters, return values, etc. Such
languages might require some extra work from the programmer upfront, but
ultimately help to prevent bugs and undesirable program behavior later.
Soon, we will get to an example of how TypeScript code looks like. But first, let’s
install it.
Start using TypeScript by creating a file index.ts . Notice the file extension. Instead
of a regular JavaScript file extension .js, we use .ts for TypeScript (or .tsx, if you
want to use JSX syntax like in React).
Let’s rewrite the JavaScript code from the beginning of this article into TypeScript:
1 let price: number; // Here we explicitly state that the variable price should be a number
2 price = 123; // This will work
3 price = "123"; // This will throw an error
4 let anotherPrice: number = 123; // We can define the type and assign value on one line as well
When you delete row #3 which now throws an error, you can run the TypeScript
Compiler on the file by writing this command in your console:
tsc index.ts
This will generate a new file index.js which contains the code converted to simple
JavaScript so that the browsers and Node.JS understand it.
You can also set the TypeScript Compiler to automatically compile your file on every
save with this command:
Let’s now have a look at the different types of variables that we can actually declare.
number
string
boolean
If you want your variable to take any type, you can simply use:
any
type | type .
Type Assertions
Let’s say we have a variable that can hold any type. We want to create another
variable with a more specific type and assign it the value of the first one. That’s
when we can use Type Assertion. For example:
Arrays in TypeScript
Array holds multiple values in a sequence. There are two ways of declaring an array
in TypeScript:
Tuples in TypeScript
Similar to arrays, tuples hold multiple elements in a sequence. However, we can
specify a different type for each element.
It’s also possible to create an array of tuples, which would have a syntax like this:
[elementType, elementType, elementType][] — notice the extra pair of square
brackets at the end.
1 let funSpell: [number, string, boolean] = [1, "Alohomora", true]; // simple tuple
2 let idList: [number, number, number, string] = [21, 12, 33, "sixty nine"]; // another simple tup
3
4 // And now an array of tuples:
5 let tupleArray: [number, string][] = [ [5, "Expelliarmus"], [7, "Lumos"] ];
Functions in TypeScript
We can specify the types of parameters as well as the types of function’s return
value.
1 // Functions
2 functions castSpell(spellId: number | string, target: string) {
3 // This function takes two parameters
4 // The first parameter spellId can hold either a numeric or a string value
5 // The second parameter target can hold a string value
6 }
7
8 // The previous function could return any value as we haven't specified the return value
9 // Let's fix it now
10 function castAdvancedSpell(spellId: number | string, target: string): string {
11 // This function has to return a string
12 return "Success!";
13 }
14
15 // If we don't want the function to return anything, we can use the void keyword
16 function noReturn(): void {
17 // This function shouldn't return a value
18 }
For example, let’s say we have a function for scoring students’ exams. Sometimes we
might score them numerically (eg. 100 points), other times we would use verbal
descriptions (“excellent”).
Let’s write a generic function for finding the most frequent score from all students.
Enum in TypeScript
Enums allow us to declare a set of named constants with numeric or string values.
Best to explain in code:
Open in app
Search
1 // These will get automatically assigned numerical values
2 enum bookCategories {
3 History, // -> 0
4 Beasts, // -> 1
5 Spells, // -> 2
6 }
7
8 // We can also assign our own numeric values
9 // If we omit a numeric value, automatically it will be the next in the sequence
10 enum spellStrengths {
11 Defensive = 5, // -> 5
12 Offensive, // -> 6
13 Fun = 10, // -> 10
14 }
15
16 // String values are not a problem either and we can mix them in with numerical values
17 enum spellNames {
18 Defensive = "EXPELLIARMUS", // -> EXPELLIARMUS
19 Offensive = "OBLIVIATE", // -> OBLIVIATE
20 Fun = "ALOHOMORA", // -> ALOHOMORA
21 SpellCount = 3, // -> 3
22 AnotherCount, // -> 4
23 }
Interface in TypeScript
Interface defines a specific structure for an object.
We can further extend our class. Let’s say we won’t to create a class for the next
generation of students, which would inherit the parents properties.
In addition to the extends keyword, let’s also demonstrate the private and
protected keywords.
1 // Extending the previous example with classes
2 class YoungerStudent extends Student {
3 private parents: string[]; // this property is only accessible in this class
4 protected relatives: string[]; // this is only accessible in this class and it's sub-classes
5
6 constructor(id: number, name: string, parents: string[], relatives: string[]) {
7 super(id, name); // We use the same initialization of properties as the parent-class
8 // But we don't have "parents" and "relatives" in the parent-class, so we initialize those
9 this.parents = parents;
10 this.relatives = relatives;
11 }
12
13 meetTheParents():void {
14 console.log(this.parents);
15 }
16 }
17
18 const potter2 = new YoungerStudent(2, "James", ["Harry", "Ginny"], ["Lilly", "Molly"]);
19
20 // We cannot directly read the private property "parents"
21 potter2.parents; // this will throw an error
22 // Instead, we can use a method, that reads the property within the class
23 potter2.meetTheParents();
TypeScript in React
A slightly different extension .tsx enables us to write JSX code in TypeScript.
Assuming you know React, this is how a simple component supporting TypeScript
might look like. We create an interface for props:
1 import * as React from "react";
2 import { render } from "react-dom";
3
4 export interface CustomPropsType {
5 title: string;
6 message?: string; // we set this prop to be optional
7 }
8
9 function App(props: CustomPropsType) {
10 return (
11 <>
12 <h1>{props.title}</h1>
13 <p>{props.message ? props.message : "No message available."}</p>
14 </>
15 );
16 }
17
18 render(<App title="Welcome" />, document.getElementById("root"));
Conclusion
Using TypeScript will make your code more resistant to bugs and unexpected
behavior. Hope this article showed you that it’s not actually that hard to start using
it.
If you found this article helpful, please click the clap 👏 button. Also, feel free to
comment! I’d be happy to help :)
Follow