Typescript cheatsheet
Typescript guidelines
Definition
- Superset of javascript which aims to ease the development of large javascript applications
- Adds common concepts such as classes, generics, interfaces and static types and allows developers to use tools like static checking and code refactoring
What does Typescript provide
- Static typing:
- Javascript is dynamically typed which means that it doesn’t know the type of your variable until it instantiates it at run-time which can cause problems and errors in your projects
- Typescript adds static type support to Javascript which takes care of bugs that are caused by false assumption of a variable type if you use it right. You still have full control over how strict you type your code or if you even use types at all
- Better IDE support: Intellisense, real-time information from the Typescript compiler, debugging…
- Access to new ECMAScript features: it gives you access to the newest ECMAScript feature and transcripts them to the ECMAScript targets of your choice -> no need to worry about browser support
Setup
1 | npm install -g typescript |
Types
Definition
Number: floating point values. All of them get the number type including binary and hex values
1
2
3let num: number = 0.222;
let hex: number = 0xbeef;
let bin: number = 0b0010;String: type to save textual data
1
2
3
4
5let str: string = 'Hello World!';
let multiStr: string = `A simple
multiline string!`
let expression = 'A new expression'
let expressionStr: string = `Expression str: ${ expression }`Boolean: true or false.
1
2let boolFalse: boolean = false;
let boolTrue: boolean = true;
Assigning Types
Single Type
1
2let str: string = 'Hello World'
This is the same with all data types.Multiple Types: using the | operator.
1
2let multitypeVar: string | number = 'String'
multitypeVar = 20
Checking Types
typeof
: it only knows about basic datatypes (Number, String, Boolean)1
2
3
4
5
6
7
8
9// create a String variable
let str: string = 'Hello World!'
// check if str is of type Number (which is always false)
if(typeof str === number){
console.log('Str is a number')
} else {
//print if it is a number or not
console.log('Str is not a number')
}instanceof
: similar to typeof except that it can also check for custom types1
2
3
4
5
6
7
8
9
10
11
12// create a custom type
class Human{
name: string;
constructor(data: string) {
this.name = data;
}
}
let human = new Human('Gabriel Belmont')
// check if it really is a variable of type Human
if(human instanceof Human){
console.log(`${human.name} is a human`)
}
Type assertions
Cast your variables to a specific datatype.
as
keyword:1
2
3let str: any = 'I am a String'
// it might even work without the cast if your TSLINT settings allow it
let strLength = (str as string).length<>
operator:1
2let str: any = 'I am a String'
let strLength = (<string>str).length
Arrays
Creation with
[]
1
let strings: string[] = ['Hello', 'World', '!']
Using the generic
Array<Type>
1
let numbers: Array<number> = [1, 2, 3, 4, 5]
Multitype arrays using the
|
operator1
let stringsAndNumbers: (string | number)[] = ['Age', 20]
Multidimensional array with
[][]
1
let numbersArray: number[][] = [[1,2,3,4,5], [6,7,8,9,10]]
Tuples
Array in which we can define what type of data can be stored in each position. That means that we can enforce types for indexes by enumerating them inside of squared brackets.
1 | // valid |
Enums
Define a set of named constants, numeric and string-based.
Numeric
1
2
3
4
5
6
7
8
9
10
11
12// initialized
enum State{
Playing = 0,
Paused = 1,
Stopped = 2
}
// non initiaized, default is 0
num State{
Playing,
Paused,
Stopped
}String
1
2
3
4
5enum State{
Playing = 'PLAYING',
Paused = 'PAUSED',
Stopped = 'STOPPED'
}
Objects
Non-primitive types are Sets of key-value pairs. These values can be variables, arrays or even functions.
1 | const human = { |
Custom Types
Typescript also lets us define custom types called alias that we easily reuse later.
1 | type Human = {firstName: string, age: number, height: number}; |
Function Parameters and return Types
1 | // define functions |
Optinal properties: using the Elvis
?
operator1
2
3
4
5
6
7
8
9
10
11function printName(firstName: string, lastName?: string) {
if (lastName){}
console.log(`Firstname: ${firstName}, Lastname: ${lastName}`);
} else {
console.log(`Firstname: ${firstName}`);
}
}
// calls: we may not add the lastName parameter
printName('Gabriel', 'Belmont')
printName('Gabriel')Default values: asssigning them at the head of the function
1
2
3function printName(firstName: string, lastName: string = 'Belmont') {
console.log(`Firstname: ${firstName}, Lastname: ${lastName}`);
}
Interfaces
They define contracts with our code as well as code outside our project. The implementation is done in the classes.
1 | interface Person{ |
Optional Properties:
?
operator1
2
3
4
5
6interface Person{
name: string
age?: number
}
const person1: Person = {name: 'Trevor', age: 32}
const person2: Person = {name: 'Gabriel'}Read-only Properties:
readonly
keyword1
2
3
4
5
6
7interface Person{
name: string
readonly id: number
age?: number
}
const person: Person = {name: 'Gabriel', id: 3127831827}
person.id = 200 // Can not assign to id because is a readonly property
Barrels
Barrels allow us to rollup several export modules in a single more convenient module.
We just need to create a new file which will export multiple modules of our project.
1 | export * from './person'; |
After doing so we can import all those modules using a single convenient import statement.
1 | import { Person, Animal, Human } from 'index'; |
Generics
Generics allow us to create components that are compatible with a wide variety of types rather than a single one.
1 | // any is generic (accepts everything) but loses the type |
Access Modifiers
Control the accessibility of the member of our classes
- Public: default, they are available from anywhere without any restriction
- Private: they can only be accessed in the class they are defined
- Protected: they can be accessed only within the class they are defined and every sub/child class
Typescript tools
TSLINT
- The standard linter for Typescript
- It help us write clean, maintainable and readable code
- It can be customized with our own lint rules, configurations, and formatters
Setup:
Install
1
2
3npm install tslint typescript
# initialize it in your project
tslint --initConfiguration: on
tslint.json
1
2
3
4
5
6
7
8
9{
"defaultSeverity": "error",
"extends": [
"tslint:recommended"
],
"jsRules": {},
"rules": {},
"rulesDirectory": []
}