Is there a way to add a default while still keeping type restrictions in a function in TypeScript?

If I have this code as follows, how do I make it so name has to be a string but also has a default of "person", something like what follows:

function greet(name = "person": string) {
  console.log(`Hello ${name}!`);
}

greet("Bob"); //Should return "Hello Bob!"
greet(1) //Should return error about having the wrong type
greet() //Should return "Hello person!"

It returns an error instead of working as intended.

>Solution :

You need to fix your type annotation for name:

function greet(name: string = "person") {
  console.log(`Hello ${name}!`);
}

Or just infer the type:

function greet(name = "person") {
  console.log(`Hello ${name}!`);
}

Edit: If you want name to be either string or number, use an union type:

function greet(name: string | number = "person") {
  console.log(`Hello ${name}!`);
}

greet("Bob"); // "Hello Bob!"
greet(1); // "Hello 1!"
greet(); // "Hello person!"

Leave a Reply