- Adds optional static types in JavaScript.
- Makes the code more expressive.
- Makes it easier to catch bugs in production.
- Can translate to various ecmaScript version.
$ npm init -y
$ npm i -D typescript
in package.json
add a dev script
"dev": "tsc --watch ."
$ ./node_modules/.bin/tsc --init
this will initialize a tsconfig.json
file with defaults and comments.
let id: number = 5
id = 'foo'
// will yield an error in typescript as id is declared to be a number
let foo: string = 'hello world!';
let bar: boolean = false;
let x: any = 'blah' // can be anything
let ages: number[] = [12, 15, 18];
let names: string[] = ['joe', 'john'];
let random: any[] = ['joe', 13.5, false, [1,2,3]]; // can be anything
let human: [string, number, boolean] = ['paul', 34, false];
let baz: string | number = 23
let baz: string | number = 'hello' // This is valid in an union
enum greet {
hi,
bye = 3,
hello
}
greet.hi // returns 0
greet.hello // returns 4 because the element before it was set to 3
type Animal = {
name: string,
age: number
}
const cat: Animal = {
name: 'Pants',
age: 3
}
// Allows optional types and readonly properties
interface Animal = {
readonly species: string, // this can only be read after declaration
name: string,
age: number,
sad?: boolean
}
const cat: Animal = {
species: 'Ginger'
name: 'Pants',
age: 3
}
cat.species = 'Something else' // will throw an error
class Animal {
protected dna: number // this can only be accesed within the class
species?: string
name: string
constructor(species: string, name: string) {
this.species = species,
this.name = name,
}
info(): void {
console.log(`${this.name} is doing fine`)
}
}
function foo<T>(items: T[]): T[] {
return [...items]
}
let names = foo<string>(['hello', 'world']) // more explicit than using any
let ages = foo<number>([12, 13, 5, 6]) // more explicit than using any
let anything: any = 2
let foo = <number>anything // We assert that anything is a number
let bar = anything as number // This also works
// returns a string
function greet(name: string, age: number): string {
return $`hello ${name}, you are ${age} years old`
}
// Does not return anything, thus "void"
function greetConsole(name: string, age: number): void {
console.log($`hello ${name}, you are ${age} years old`)
}