乐闻世界logo
搜索文章和话题

How to declare a function with typed annotation in TypeScript?

1个答案

1

In TypeScript, declaring functions with type annotations primarily involves two aspects: type annotation for function parameters and type annotation for function return values. This helps increase type safety when writing code and makes the code more understandable and maintainable. Below, I will demonstrate how to declare functions and add type annotations in TypeScript through a specific example.

Assume we need to write a function that takes two parameters: a string and a number, and returns a string. In TypeScript, we can declare this function as follows:

typescript
function createGreeting(name: string, age: number): string { return `Hello, my name is ${name} and I am ${age} years old.`; }

In this function declaration:

  • name: string indicates that the parameter name is of string type.
  • age: number indicates that the parameter age is of number type.
  • The : string after the function name indicates that the return value is of string type.

This kind of type declaration not only helps developers clearly understand the types of each parameter and return value but also, when using modern IDEs, provides real-time type checking and auto-completion features, significantly improving development efficiency and reducing bugs caused by type errors.

Additionally, if a function has no return value, we can use the void type to indicate this, for example:

typescript
function printGreeting(name: string, age: number): void { console.log(`Hello, my name is ${name} and I am ${age} years old.`); }

Through such type annotations, TypeScript provides powerful type checking during the compilation phase, helping developers catch potential errors and ensure code quality.

2024年11月29日 09:32 回复

你的答案