DEV Community

Manthan Ankolekar
Manthan Ankolekar

Posted on

1

Convert simple javascript function to typescript

Here's a simple JavaScript function that calculates the square of a number:

function calculateSquare(number) {
  return number * number;
}

// Usage example
const inputNumber = 5;
const result = calculateSquare(inputNumber);
console.log(`The square of ${inputNumber} is ${result}`);
Enter fullscreen mode Exit fullscreen mode

Here's the same function converted to TypeScript:

function calculateSquare(number: number): number {
  return number * number;
}

// Usage example
const inputNumber: number = 5;
const result: number = calculateSquare(inputNumber);
console.log(`The square of ${inputNumber} is ${result}`);
Enter fullscreen mode Exit fullscreen mode

In TypeScript, you can specify the types of function parameters and return values using the : notation. In this case, we've specified that the number parameter should be of type number, and the return value of the function is also of type number. The rest of the code remains very similar to the JavaScript version.

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more