Home > Software engineering >  How to convert a simple JavaScript function into TypeScript function?
How to convert a simple JavaScript function into TypeScript function?

Time:11-27

I'm Java developer and I started learning TypeScript for frontend. And I have a very simple piece of JavaScript code and I want to convert it to TypeScript code.

This is the JavaScript code:

let numbers = [123, 234, 345, 456, 567];
let names = ['Alex', 'Bree', 'Cara', 'Cole', 'Devon', 'Riley'];

let bigA = numbers.filter(function(item)) {
    return item > 300;
}

And here is the TypeScript code:

let numbers: number[] = [123, 234, 345, 456, 567];
let names: string[] = ['Alex', 'Bree', 'Cara', 'Cole', 'Devon', 'Riley'];

let big: number[] = numbers.filter(function(item)) {
    return item > 300;
}

But there is an error for item: "Binding element 'item' implicitly has an 'any' type.ts(7031) ", but it's not working if I put return item: number > 300;

I don't want to use this style let big: number[] = numbers.filter((item) => item > 300);

Do you know how to resolve it? Thank you!

CodePudding user response:

You have closed your brackets in the wrong place. The closing brackets will be in the last line:

wrong code

Try this (Right code):

let numbers: number[] = [123, 234, 345, 456, 567];
let names: string[] = ['Alex', 'Bree', 'Cara', 'Cole', 'Devon', 'Riley'];

let bigA: number[] = numbers.filter(function(item: number){
    return item > 300;
})
  • Related