Using typescript type information inside javascript files

Viewed 17

if I have a file, for example Person.ts that looks like:

class Person {
  name: string
  
  constructor(name: string) {
    this.name = name
  }
}

module.exports = Person;
export default Person;

And after that, I have a javascript file that imports it and uses it like so:

const Person = require("./Person")

const person = new Person("Joe")

console.log(person.name)

It gives me an error (in my editor) that looks like:

Property 'name' does not exist on typeof import("<whatever>/Person").

What I can understand is that Javascript uses the Person class from the compiled TS file, so it loses type information, but because I have enabled JS checking inside my tsconfig, it now gives an error.

Is there any way I can keep the types while importing from TS files into JS? I have tried ES6 imports too, and it results into the same problem.

Sadly renaming the file to .ts is not an option as of now.

0 Answers
Related