'How to preload typescript class with -r option of ts-node

Suppose there is a file named lib.ts with the following content:

export class A {}
console.log('script loaded');

Now I start ts-node REPL this way: npx ts-node -r ./lib.ts Then I can see it prints "script loaded" which confirms that the script has been processed.

But when I run the following statement in the REPL

const a = new A()

It just throws the error error TS2304: Cannot find name 'A'.

For some reason I need to preload the class I define in the lib.ts but it seems not work well. What was wrong and how to fix it, or is there any other workaround?



Solution 1:[1]

A simple solution I found is to just assign them to the global.

class A {}
class B {}

Object.assign(global, {
  A,
  B,
})

console.log('script loaded');

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 link89