Issue
I have a simple script trying to test out top level await with Node & TypeScript.
import { readFile } from "fs/promises";
async function getNum(filename: string) {
return parseInt(await readFile(filename, "utf8"), 10);
}
try {
const numberPromises = [1, 2, 3].map((i) => getNum(`${i}.txt`));
const numbers = await Promise.all(numberPromises);
console.log(numbers[0], numbers[1], numbers[2]);
} catch (err) {
console.error("Something went wrong");
console.error(err);
}
I get this error when I try to compile with TypeScript:
error TS1378: Top-level 'await' expressions are only allowed when the 'module' option is set to 'es2022', 'esnext', 'system', or 'nodenext', and the 'target' option is set to 'es2017' or higher.
It's triggered by the top-level await on line9:
const numbers = await Promise.all(numberPromises);
I'm confused because I have done both of the things mentioned in the error message and I have tried to pair down my tsconfig.json as much as possible.
{
"compilerOptions": {
"module": "es2022",
"target": "es2017",
"outDir": "dist",
"strict": true,
"moduleResolution": "Node"
}
}
I also have type: module in my package.json file.
{
"name": "ts-test",
"version": "1.0.0",
"type": "module",
"devDependencies": {
"@types/node": "^17.0.5",
"typescript": "^4.6.0-dev.20211226"
},
"scripts": {
"dev": "node dist/script.js",
"compile": "tsc script.ts"
},
"author": "Todd Matthews",
"license": "ISC",
"volta": {
"node": "17.3.0"
}
}
Any help on how I could test out top-level await with Node and TypeScript would be greatly appreciated!
Solution
I'll provide a simpler reproduction case for you which doesn't rely on any filesystem API, and I'll include all repo files and commands:
Files
./package.json:
{
"name": "so-70491077",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "dist/main.ts",
"scripts": {
"test": "tsc && node dist/main.js"
},
"author": "",
"license": "MIT",
"devDependencies": {
"typescript": "^4.5.4"
}
}
./tsconfig.json:
{
"compilerOptions": {
"module": "es2022",
"target": "es2017",
"outDir": "dist",
"strict": true,
"moduleResolution": "Node"
},
"files": ["main.ts"]
}
./main.ts:
export async function getRandom (): Promise<number> {
return Math.random();
}
const n = await getRandom();
console.log(n);
Commands
cd /path/to/the/dir/where/you/stored/the/files/above
npm i
npm test
Output
> so-70491077@1.0.0 test
> tsc && node dist/main.js
0.9303778211654203 # a similar floating point number
Answered By - jsejcksn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.