Example 1: typescript integer
const myInt: number = 17;
const myDecimal: number = 17.5;
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: use type as value typescript
Typescript interfaces aren''t being compiled into the js output, and you can not use them at runtime
Example 4: 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 5: typescript object type
let endedCoord: {x: number, y: number} = {
x: -1,
y: -1,
}
Example 6: typing in typescript
var name: string = "Anna";
let notes: (number | string)[] = ["Get Food", 23, "Call the previous number when betting"];