Strong typing of functions as parameters in TypeScript: how to declare a type for a callback?
Hello everyone! I recently started learning TypeScript and encountered a problem when passing functions as arguments. In JavaScript, I often did this:
```typescript
function processData(data, callback) {
const result = data.map(item => item * 2);
callback(result);
}
processData([1, 2, 3], function(result) {
console.log(result);
});
```
But in TypeScript, I need to specify types, and I don't understand how to properly declare the type for a function parameter. I tried several options, but they don't work:
```typescript
// Option 1: just specify any
function processData(data: number[], callback: any) { ... }
// Option 2: Function
function processData(data: number[], callback: Function) { ... }
```
The first option defeats the whole purpose of TypeScript — type checking is lost.
No answers yet.
Log in to leave an answer
Blogs
Working with Databases in PHP: PostgreSQL and MongoDB