Typescript

Poby’s Home
2 min readNov 22, 2020

Basic Types

// 1. boolean
let isDone: boolean = false;
// 2. number
let decimal: number = 6;
// 3. string
let color: string = "blue";
// 4. Array
let list: number[] = [1, 2, 3];
let list: Array<number> = [1, 2, 3];
// 5. Tuple
let x: [string, number];
x = ["hello", 10];
// 6. enum
enum Color
Red,
Green,
Blue
}
let c: Color = Color.Green;
// 7. any// 8. void// 9. null // 10. undefined// 11. never// 12. object
declare function create(o: object | null): void;
create({ prop:0 }); // OK
create(null); // OK
create(42); // Error

Type assertions → casting in other languages. (Prefer type declaration to type assertion. )

let someValue: any = "this is a string";let strLength: number = (<string>someValue).length;
//or
let strLength: number = (someValue as string).length;

Function annotation

// Function statement
function greeter1(a: string, b: string): string {
return a + b;
}
// Function Expression
const greeter2 = function(a: string, b: string): string {
return a + b
}
// Function Expression
const greeter3 = (a: string, b: string): string => {
return a + b;
};
// Function Expression
type StringBinaryFn = (a: string, b: string) => string;
const greeter4: StringBinaryFn = (a, b) => {
return a + b;
};

Interface

interface SquareConfig {   
color?: string;
width?: number;
}
// readonly vs const
// Variables use const whereas properties use readonly.
interface Point {
readonly x: number;
readonly y: number;
}

Function Types: function signature declare

interface SearchFunc {   
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
let result = source.search(subString);
return result > -1;
};

Indexable Types

interface StringArray {   
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
let myStr: string = myArray[0];

Class Types

interface ClockInterface {   
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) {}
}

Extending Interfaces

interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}

let square = {} as Square;
square.color = "blue";
square.sideLength = 10;
interface Shape { color: string; }
interface Square extends Shape {
sideLength: number;
}
let square = {} as Square;
// do not use below because it will cause "TypeError: Cannot set property 'color' of undefined"
// let square: Square;
square.color = "blue";
square.sideLength = 10;

--

--