Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the TypeScript equivalent to `var x = require("somemod")();`

In node.js I'm using jsreport-core and they do their import like var jsreport = require('jsreport-core')(); with the trailing (). I'm curious what is the best way to replicate this import technique is in TypeScript?

like image 482
Jason Leach Avatar asked Mar 21 '16 04:03

Jason Leach


People also ask

What is the difference between let and Var in typescript?

In the above example, the TypeScript compiler will give an error if we use variables before declaring them using let, whereas it won't give an error when using variables before declaring them using var.

What is import type in typescript?

Import types. You can also import declarations from other files using import types. This syntax is TypeScript-specific and differs from the JSDoc standard: import types can be used to get the type of a value from a module if you don’t know the type, or if it has a large type that is annoying to type:

How do you reference a type in typescript?

You can use the “@type” tag and reference a type name (either primitive, defined in a TypeScript declaration, or in a JSDoc “@typedef” tag). You can use most JSDoc types and any TypeScript type, from the most basic like string to the most advanced, like conditional types.

Why TypeScript doesn't know what require is?

So when you type const x = require ('x'), TypeScript is going to complain that it doesn't know what require is. You need to install @types/node package to install type definitions for the CommonJS module system in order to work with it from the TypeScript. Let's imagine you have a.ts and x.js as source files.


2 Answers

I'm curious what the best way to replicate this import technique is in TypeScript

You need to split the import and the function call:

import jsreportCreator = require('jsreport-core');
const jsreport = jsreportCreator();
like image 153
basarat Avatar answered Sep 22 '22 00:09

basarat


I am pulling in the "@types/jsreport-core": "^1.5.1" in package.json's devDependencies and am using an import, for example:

import JsReport from 'jsreport-core';

const jsReport = JsReport({
    loadConfig: true
});
like image 42
andyb Avatar answered Sep 20 '22 00:09

andyb