Using TypeScript Object in JavaScript File

Viewed 28

The Scenario

I have a class where I want to use TypeScript to ensure all properties are of a specific type.

// MyTypeScriptClass.ts

class MyTypeScriptClass {
  name: string
  description: string
  counter: number

  constructor(name: string, description: string) {
    this.name = name
    this.description = description
    this.counter = 0
  }
}

I then have a JavaScript file where I'd like to then use MyTypeScriptClass as the object to parse JSON from HTTP request.

// MyJavaScriptFetchRequest.js

// TODO: import/require `MyTypeScriptClass`
const axios = require('axios')

function fetch() {
  const url = "https://api.that.i.want.com/endpoint"
  const call = axis.get(url)
  call.then((response) => {
    const jsonString = JSON.stringify(response.data)
    const data = JSON.parse(jsonString)
    
    // TODO: Convert the Object `data` to `MyTypeScriptClass`

  })
}

module.exports = { fetch: fetch() }

The Problem I run into is

  1. I cannot use import 'MyTypeScriptClass' because it results in a Syntax Error: Cannot use import statement outside a module
  2. I cannot use require('MyTypeScriptClass') because it results in a `Error: Cannot find module 'MyTypeScriptClass'.

My Question

  1. How do I use a TypeScript Object in a JavaScript file?
  2. How do I convert a JSON JS object to a TypeScript Object?
0 Answers
Related