Example 1: typescript union types
type Cow = {
name: string;
moo: () => void;
};
type Dog = {
name: string;
bark: () => void;
};
type Cat = {
name: string;
meow: () => void;
};
type Animals = Cow | Dog | Cat;
Example 2: typescript type definition
const name: string = "john doe"
const age: number = 30
const days1: string[] = ["sunday","monday","thuesday","wenesday"]
const numb1: number[] = [1,2,3,4,5]
const days2: Array<string> = ["sunday","monday","thuesday","wenesday"]
const numb2: Array<number> = [1,2,3,4,5]
const person: Record<string, any> = {
name: "john doe",
age: 30
}
async function name(): Promise<string> {
return "john doe"
}
name().then(console.log)
async function str(): Promise<string[]> {
return ["sunday","monday","thuesday","wenesday"]
}
str().then(console.log)
async function int(): Promise<int[]> {
return [1,2,3,4,5]
}
int().then(console.log)
async function objectValue(): Promise<Record<string, any>> {
const person: Record<string, any> = {
name: "john doe",
age: 30
}
return person
}
objectValue().then(console.log)
async function objectValueMulti(): Promise<Record<string, any>[]> {
const person: Record<string, any>[] = [{
name: "john doe",
age: 30
},{
name: "jane doe",
age: 30
}]
return person
}
objectValueMulti().then(console.log)
Example 3: custom types in typescript
type Websites = 'www.google.com' | 'reddit.com';
let mySite: Websites = 'www.google.com'
let mySite: Website = 'www.yahoo.com'
type Details = { id: number, name: string, age: number };
let student: Details = { id: 803, name: 'Max', age: 13 };
let student: Details = { id: 803, name: 'Max', age: 13, address: 'Delhi' }
let student: Details = { id: 803, name: 'Max', age: '13' };
Example 4: type gurad
1) Type guards narrow down the type of a variable within a conditional block.
2) Use the 'typeof' and 'instanceof operators to implement type guards in the
conditional blocks.
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
(instanceof)
if (job instanceof detail){
jobless = false ;
}
Example 5: typescript
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);