What is typescript?
Typescript is an open-source language and is a superset of javascript.
Offers additional features to javascript including static types
Using types is completely optional
Compiles down to regular JS
Can be used for frontend JS as well as backend with Node.js
Includes most features from ES6, ES7 (Classes, Arrow, Functions etc).
Types from third party libraries can be added with type definitions.
Static Examples: Java, C, C++, Rust, Go.
Dynamic Examples: Javascript, Python, Ruby, PHP.
Advantages & Disadvantage:
Compiling Typescript:
Typescript uses .ts and .tsx extensions
TSC (Typescript compiler) is used to compile .ts files down to JS
Can watch files and report errors at compile time
Many tools includes TS compilation by default
More IDS's have great support for TS
The tsconfig.js files is used to configure how Typescript works
Install Typescript
sudo npm i -g typescript
Check installation
tsc -v
Run file
tsc index
// Basic Types
let id: number = 5
let company: string = 'Esenceweb IT'
let isPublished: boolean = true
let x: any = 'Hello'
let ids: number[] = [1, 2, 3, 4, 5]
let arr: any[] = [1, true, 'Hello']
// Tuple
let person: [number, string, boolean] = [1, 'Rohan', true]
// Tuple Array
let employees: [number, string][]
employee = [
[1, 'Rohan'],
[2, 'John'],
[3, 'Jill'],
]
// Union
let pid: string | number
pid = '22'
// Enum
enum Direction1 {
Up = 1,
Down,
Left,
Right,
}
enum Direction2 {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right',
}
// Objects
type User = {
id: number
name: string
}
const user: User = {
id: 1,
name: 'John',
}
// Type Assertion
let cid: any = 1
// let customerId =
let customerId = cid as number
// Functions
function addNum(x: number, y: number): number {
return x + y
}
// Void
function log(message: string | number): void {
console.log(message)
}
// Interfaces
interface UserInterface {
readonly id: number
name: string
age?: number
}
const user1: UserInterface = {
id: 1,
name: 'John',
}
interface MathFunc {
(x: number, y: number): number
}
const add: MathFunc = (x: number, y: number): number => x + y
const sub: MathFunc = (x: number, y: number): number => x - y
interface PersonInterface {
id: number
name: string
register(): string
}
// Classes
class Person implements PersonInterface {
id: number
name: string
constructor(id: number, name: string) {
this.id = id
this.name = name
}
register() {
return `${this.name} is now registered`
}
}
const john = new Person(1, 'john Doe')
const mike = new Person(2, 'Mike Jordan')
// Subclasses
class Employee extends Person {
position: string
constructor(id: number, name: string, position: string) {
super(id, name)
this.position = position
}
}
const emp = new Employee(3, 'Shawn', 'Developer')
// Generics
function getArray
return new Array().concat(items)
}
let numArray = getArray
let strArray = getArray
strArray.push(1) // Throws error
0 Replies to “Typescript Crash Course For Beginners”
Leave a Reply
Your email address will not be published.