typescript optional type code example
Example 1: typescript optional parameters
sayHello(hello?: string) {
console.log(hello);
}
sayHello();
sayHello('world');
Example 2: how to define optional parameter in typescript
function functionName(par1: number, par2?: number) {
}
Example 3: typescript optional parameters
sayHello(hello: string = 'hello') {
console.log(hello);
}
sayHello();
sayHello('world');
Example 4: how to make a parameter optional in typescript
function foo(x?: number) {
console.log("x : "+ x);
}
foo();
foo(6);
Example 5: 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 6: typescript interface
interface LabeledValue {
label: string;
}
function printLabel(labeledObj: LabeledValue) {
console.log(labeledObj.label);
}
let myObj = { size: 10, label: "Size 10 Object" };
printLabel(myObj);Try