I am learning Typescript and ran into the following problem with Node.js worker threads:
In a tutorial I found this JS code to be implemented by the worker:
//worker.js
const {parentPort} = require("worker_threads");
parentPort.on("message", data => {
parentPort.postMessage({num: data.num, fib: getFib(data.num)});
});
function getFib(num) {
if (num === 0) {
return 0;
}
else if (num === 1) {
return 1;
}
else {
return getFib(num - 1) + getFib(num - 2);
}
}
... together with this parent thread:
//app.js
const {Worker} = require("worker_threads");
//Create new worker
const worker = new Worker("./worker.js");
//Listen for a message from worker
worker.on("message", result => {
console.log(`${result.num}th Fibonacci Number: ${result.fib}`);
});
worker.on("error", error => {
console.log(error);
});
worker.postMessage({num: 40});
worker.postMessage({num: 12});
As an exercise I wanted to transfer this into Typescript. When I want to implement this
//types.ts
type CalcValue = {
num: number;
fib: number;
}
... the following seems to work fine
//app.js
import {CalcValue} from "./types";
const {Worker} = require("worker_threads");
//Create new worker
const worker = new Worker("./worker.js");
//Listen for a message from worker
worker.on("message", (result: CalcValue) => {
console.log(`${result.num}th Fibonacci Number: ${result.fib}`);
});
worker.on("error", (error: any) => {
console.log(error);
});
... but when I want to add the same typing in the worker file, I get error messages.
//worker.ts
import {CalcValue} from "./types";
const {parentPort} = require("worker_threads");
parentPort.on("message", (data: CalcValue) => {
parentPort.postMessage({num: data.num, fib: getFib(data.num)});
});
function getFib(num: number): number {
if (num === 0) {
return 0;
}
else if (num === 1) {
return 1;
}
else {
return getFib(num - 1) + getFib(num - 2);
}
}
[1] import CalcValue from "./types";
[1] ^^^^^^
[1]
[1] SyntaxError: Cannot use import statement outside a module
How would I solve this?