What typescript is?
Typescript is a superset of javascript. Any valid javascript code also valid typescript code.
Typescript has strong typing, Object-oriented, Compile-time errors. Typescript can’t directly run on a browser, it has to transpile to ES5 javascript.
How can we install typescript on our machine.
// Mac
sudo npm install -g typescript
All typescript code file has to be end with .ts extension.
Let get started.
// const vs let
const cannotChange = 10;
let canChange = 'abc';
// Type
// by default, typescript variables has to specifi a type on each variable
// Number
let decimal: number = 10;
let hex: number = 0xf00d;
// String
let person: string = "john";
let age: number = 30;
// Array
let data: number[] = [ 1, 2, 3 ];
// Boolean
let isEdit: boolean = true;
let done: boolean = false;
//Tuple
let x: [string, nubmer];
x = ["hi", 1]; // ok
x = [11, lol]; // Error
//Function
function greeting(person: string) {
return `hello, ${person}`;
}
// Interface
interface Person {
firstName: string;
lastName: string;
}
function greeting(person: Person) {
return `hello, my name is: ${person.firstName} ${person.lastname}`;
}
let user = {
firstName: "John",
lastName: "Smith",
};
console.log(greeting(user));
// Classes
class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = `${firstName} ${middleInitial} ${lastName}`;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person : Person) {
return `Hello, ${person.firstName} ${person.lastName}`;
}
let user = new Student("Jane", "M.", "User");
console.log(greeter(user));