Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading