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
- I cannot use
import 'MyTypeScriptClass'because it results in aSyntax Error: Cannot use import statement outside a module - I cannot use
require('MyTypeScriptClass')because it results in a `Error: Cannot find module 'MyTypeScriptClass'.
My Question
- How do I use a TypeScript Object in a JavaScript file?
- How do I convert a JSON JS object to a TypeScript Object?