function runFn(fn: (arg: number) => any, value: number): any {
return fn(value);
}
runFn
would accept a function that takes a single number as an argument and returns any value. runFn
would take in such a function, plus a number value, and then execute that function with the value.
Note that here we use the arrow notation to indicate what the passed function returns, not a colon as we do the main function signature.
Building a TypeScript project
Many build tools in the JavaScript ecosystem are now TypeScript-aware. For instance, the frameworks tsdx, Angular, and Nest all know how to automatically turn a TypeScript codebase into its matching JavaScript code with little intervention on your part.
If you’re working with a build tool like Babel or webpack (among others), those tools can also handle TypeScript projects, as long as you install TypeScript handling as an extension or enable it manually. For instance, with webpack, you’d install the ts-loader
package through npm
, and then set up a webpack.config.js
file to include your .ts
files.
The key to moving an existing JavaScript project to TypeScript is to approach it a step at a time—migrate one module at a time, then one function at a time. Because TypeScript can coexist with regular JavaScript, you are not obliged to migrate everything at once, and you can take the time to experiment with figuring out the best types to use across your project’s codebase.