typescript is type code example

Example 1: typescript check type

mySprite instanceof Sprite;

Example 2: typescript type definition

// cannot use object for type defination because this is not recommended
// use Record this same with object

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 = ["sunday","monday","thuesday","wenesday"]
const numb2: Array = [1,2,3,4,5]

const person: Record = {
	name: "john doe",
	age: 30
}

async function name(): Promise {
	return "john doe"
}

name().then(console.log)

async function str(): Promise {
	return ["sunday","monday","thuesday","wenesday"]
}

str().then(console.log)

async function int(): Promise {
	return [1,2,3,4,5]
}

int().then(console.log)

async function objectValue(): Promise> {
	const person: Record = {
	 name: "john doe",
	 age: 30
	}
  return person
}

objectValue().then(console.log)

async function objectValueMulti(): Promise[]> {
	const person: Record[] = [{
	 name: "john doe",
	 age: 30
	},{
	 name: "jane doe",
	 age: 30
	}]
  return person
}

objectValueMulti().then(console.log)

Example 3: custom types in typescript

// simple type
type Websites = 'www.google.com' | 'reddit.com';
let mySite: Websites = 'www.google.com' //pass
//or
let mySite: Website = 'www.yahoo.com' //error
// the above line will show error because Website type will only accept 2 strings either 'www.google.com' or 'reddit.com'.
// another example. 
type Details = { id: number, name: string, age: number };
let student: Details = { id: 803, name: 'Max', age: 13 }; // pass
//or 
let student: Details = { id: 803, name: 'Max', age: 13, address: 'Delhi' } // error
// the above line will show error because 'address' property is not assignable for Details type variables.
//or
let student: Details = { id: 803, name: 'Max', age: '13' }; // error
// the above line will show error because string value can't be assign to the age value, only numbers.

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.
   
//example(typeof)
if (typeof a === 'number' && typeof b === 'number') {
    return a + b;
}

(instanceof)
if (job instanceof detail){
	jobless = false ;
}

Tags:

Misc Example