Example 1: how to declare variable in typescript
const variableSample: number = 0;
let variableSample: number = 0;
Example 2: 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 3: typescript type declaration
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 4: variable declare in ts
let a:number =1
let b:Boolean = true
let c:string = "Grepper"
Example 5: typescript declare global
ts
declare function myLib(a: string): string;
declare function myLib(a: number): number;
interface myLib {
name: string;
length: number;
extras?: string[];
}
declare namespace myLib {
let timeout: number;
const version: string;
class Cat {
constructor(n: number);
readonly age: number;
purr(): void;
}
interface CatSettings {
weight: number;
name: string;
tailLength?: number;
}
type VetID = string | number;
function checkCat(c: Cat, s?: VetID);
}