Saturday, August 3, 2024
Typescript for noobs
Why?
In languages like C or Java, we have variable and function types that we always have to declare. And we can also declare a template in which it is determined which type of file we can have in a variable, function or structure. What are the advantages?
function hello(mustBeString){
if (typeof mustBeString !== 'string'){
throw 'Argument nije string!';
}
}
So now we are wasting time checking the argument type. In typescript we write like this:
function hello(mustBeString: string){
//...
}
We can also specify the allowed type returned by the function:
function hello(n: number) : number{
return n++;
}
So now we don't have to check the value returned by the function.
Installation
sudo apt install node-typescript #ubuntu
This allows us to use the "tsc" command globally. So we are preparing a project with:
mkdir project
cd ./project
tsc --init
mkdir src
cd ./project/src
touch ./index.ts
tsconfig.json
"tsconfig.json" is created for us by the "tsc -init" command. This file must be studied and it contains settings and comments with explanations.
In “index.ts” add:
function render(n: number) : number{
return n++;
}
render(232);
We compile the code with the "tsc" command. So in the directory where "tsconfig.json" is, we enter the command:
tsc
And now in the "/src" directory we also have a compiled ordinary "index.js".
"use strict";
function render(n) {
return n++;
}
render(232);
Type
number |
string |
boolean |
null |
undefined |
object |
any |
unknown |
never |
enum |
tuple |
Examples
Code |
Description |
let age: number = 20; |
broj |
let sales: number = 123_456_789; |
Numbers can be separated with underscore char “_” |
let course: string = ‘TypeScript’; |
string |
let isPublished: boolean = true; |
bool |
let level; |
type: any |
let numbers: number[] = [1,2,3]; |
array, only with numbers |
Tuple
A tuple is an array with certain values.
let user: [number,string] = [1, 'alpha'];
Enum
As in the C language with enum, we add a series of variables that become enumerated. Which means that each variable gets a number in the sequence and starts with zero.
const enum Size { Small, Medium, Large};
So here “Size.Medium” is equal to the number 1.
enum Size { Small=2, Medium, Large};
Here the enumeration starts with the number 2.
Unlike the C language, in TS an enum can be a string, but then all values must be a string.
enum Size { Small='s', Medium='m', Large='l' };
Object
We declare the structure of the object like this:
let employee: {
id: number,
name: string
} = {
id:1,
name:''
};
employee.name = 'Alpha';
Read only
let something: {
readonly id: number,
} = {
id:1
};
Optional property
If we do not enter all the properties in the declared object, we get an error. To get around that, we use the "optional property".
let employee: {
id: number,
name?: string // ?: optional property
} = {
id:1
};
Methods
We declare the methods like this:
let employee: {
id: number,
retire: (date: Date) => void,
} = {
id:1,
retire: (date: Date) => {
console.log(date);
},
};
Type Alias
We declare a new type "Employee" and use it as built-in types:
type Employee = {
id: number,
retire: (date: Date) => void,
}
let employee: Employee = {
id:1,
retire: (date: Date) => {
console.log(date);
},
}
Union types
How to allow multiple types:
function kgToLbs(weight:number|string): number{
if (typeof weight === 'number') ...
};
kgToLbs(10);
kgToLbs('10kg');
Intersection types
Self-explanatory in the example:
type Draggable = {
drag: () => void
};
type Resizable = {
resize: () => void
};
type UIWidget = Draggable & Resizable;
let textBox: UIWidget = {
drag: () => {},
resize: () => {},
}
Literal type
We specify only allowed values.
let quantity: 50 | 100; // može biti 50 ili 100
let quantity: Quantity;
type Metric = 'cm' | 'inch';
NULL
Types CANNOT be "null" or "undefined", so we must specify them:
type Value = string | null | undefined;
To be continued…