Can you identify and correct it?function greet(name: string) { console.log("Hello, " + name);}greet(123);What is the error, and how would you correct it?
Question
Can you identify and correct it?
function greet(name: string) {
console.log("Hello, " + name);
}
greet(123);
What is the error, and how would you correct it?
Solution
Identifying the Error
- Type Mismatch: The function
greet
is defined to take a parameter of typestring
, but it is being called with a number (123). - TypeScript Strictness: TypeScript checks types at compile time, and passing a number to a function that expects a string will throw an error.
Correcting the Error
-
Change the Argument: The simplest correction is to ensure that the argument passed to the function is of type
string
. You can change the call fromgreet(123);
togreet("123");
.function greet(name: string) { console.log("Hello, " + name); } greet("123"); // Corrected call with string argument
-
Type Conversion: Alternatively, if you want to allow numbers and convert them to strings inside the function, you can modify the function to accept a parameter of type
any
ornumber
, and then cast it to a string.function greet(name: any) { console.log("Hello, " + String(name)); // Converting to string } greet(123); // This will now work correctly
Summary
The initial call greet(123);
produces a type error due to the mismatch in expected parameter type. By passing a string or modifying the function to accept numbers, the error can be resolved effectively.
Similar Questions
Can you identify and correct it?function greet(name: string) { console.log("Hello, " + name);}greet(123);What is the error, and how would you correct it?
Determine the error in the code below.var str = "Hello\nWorld";ADouble-quote strings can't span multiple lines.BThere is no error
What would be logged to the console by the following block of code?let a = "ILoveProgramming"; let result = a.substring(3, 6);console.log(result);vePILogniing
What is the output of this code?let str="Hello world ! This is a wonderful day.";console.log(s.lastIndexof('w'));
What will the below statements print on the console?"use strict"function abc() {console.log(this);}abc();
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.