optional type typescript code example

Example 1: typescript optional parameters

// Optional Parameters
sayHello(hello?: string) {
	console.log(hello);
}

sayHello(); // Prints 'undefined'

sayHello('world'); // Prints 'world'

Example 2: how to define optional parameter in typescript

function functionName(par1: number, par2?: number) {

}

Example 3: typescript optional parameters

// Default Parameters
sayHello(hello: string = 'hello') {
  console.log(hello);
}

sayHello(); // Prints 'hello'

sayHello('world'); // Prints 'world'

Example 4: how to make a parameter optional in typescript

// Optional parameter
function foo(x?: number) {
    console.log("x : "+ x);
}
foo();
foo(6);

Example 5: 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 6: 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 ;
}