Example 1: typescript get type
if (typeof abc === "number") {
}
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' };