optional 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: typescript optional parameters

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

sayHello(); // Prints 'hello'

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

Example 3: how to make a parameter optional in typescript

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

Example 4: 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