How to bring in a class that was exported using `export = uuid` in Typescript

I'm facing a challenge while working with the node_module called uuid-js in TypeScript. After installing both the module and its typings, I am unsure how to properly import the module.

Question: What is the correct way to import the module?


The function I intend to use is uuid.create, which is defined in the typings of uuid-js as follows:

export = uuid;
declare class uuid {
    equals(uuid: uuid): boolean;
    ... 
    static create(version?: number): uuid;
    ...
}

The TypeScript documentation mentions that:

When using export = to import a module, you must make use of TypeScript-specific import module = require("module") syntax for importing the module.

Based on this information, it seems like I should do the following:

import UUID = require('uuid-js');

Which would then compile to this:

const UUID = require("uuid-js")  

Is there a specific reason why I should use import instead of const in my code? Could I not just directly utilize the compiled code?

Using require altogether feels somewhat peculiar. Perhaps, it might be better to avoid using the typings or exploring an alternative approach...?

So, what exactly sets apart the usage of:

import UUID = require('uuid-js');

From

const UUID = require("uuid-js")  

I did attempt a more conventional import method recommended by Madara Uchiha, but encountered errors.

For instance, using import * as UUID from 'uuid-js' led to:

error TS2497: Module '".../node_modules/@types/uuid-js/index"' resolves to a non-module entity and cannot be imported using this construct.

Similarly, trying import UUID from 'uuid-js'; resulted in:

error TS1192: Module '".../node_modules/@types/uuid-js/index"' has no default export.

Answer №1

Before ES2015 modules were introduced, TypeScript came up with the

import something = require('something')
and export = something syntaxes.

However, now we prefer using the standard module syntax:

import * as UUID from 'uuid-js'; // if uuid-js does not have export default
// or
import UUID from 'uuid-js'; // if it does.

The typings code you provided suggests that you should opt for the former approach.

Answer №2

What sets them apart?

import brings in the types, while const/require does not include them.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is the AngularJS 2 child @Component not being replaced in this scenario?

UPDATE: It seems that the issue lies in how I am structuring and serving the project rather than a coding problem. If I find a solution, I'll be sure to update this post. Thank you for your assistance. I'm currently developing an AngularJS 2 ap ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths. This is how my tsconfig.json looks: { "compilerOptions": { "target": "ES2 ...

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

Ways to ensure that when changes occur in one component, another component is also updated

How can I update the cart badge value in the navbar component every time a user clicks the "Add to Cart" button in the product-list component? The navbar component contains a cart button with a badge displaying the number of products added to the cart. n ...

The attribute 'NameNews' is not recognized in the specified type when running ng build --prod

Definition export interface INewsModule{ IDNews:number; IDCategoery:number; NameNews:string; TopicNews:string; DateNews?:Date; ImageCaption:string; ImageName:string ; } Implementation import { Component, OnInit, Input, I ...

Is it possible to retrieve a constant value while developing a customized rule in typescript-eslint?

I am currently working on implementing a custom ESLint rule using @typescript-eslint/utils that will display a warning if the prop kind of Category does not match a specific Regex pattern: import { ESLintUtils, TSESTree } from '@typescript-eslint/util ...

Refining types in a series of statements

I'm attempting to merge a series of assertions in a safe manner without the need to individually call each one. For instance, consider the following code: type Base = { id: string, name?: string, age?: number }; type WithName = { name: string }; type ...

Hey there world! I seem to be stuck at the Loading screen while trying to use Angular

A discrepancy in the browsers log indicates node_modules/angular2/platform/browser.d.ts(78,90): error TS2314: Generic type 'Promise' is missing 2 type arguments. ...

Selecting the optimal data structure: weighing the benefits of using boolean check versus array .include (balancing performance and redundancy

My objects can have one or more properties assigned, with a total of 5 different properties in my case. To illustrate this, let's use a simple movie example where each movie can be assigned from 5 different genres. I have come up with two methods to ...

Is it possible to enforce a certain set of parameters without including mandatory alias names?

My inquiry pertains to handling required parameters when an alias is satisfied, which may seem complex initially. To illustrate this concept, let's consider a practical scenario. If we refer to the Bing Maps API - REST documentation for "Common Param ...

Adjust the background color of the header as you scroll

Seeking assistance in adjusting the background color of my header upon scrolling. This is my current implementation: header.component.ts export class HeaderComponent { ngOnInit(): void { const header = document.querySelector('.header'); ...

The projection of state in NGRX Store.select is not accurately reflected

Every time I run the following code: valueToDisplay$ =store.select('model','sub-model') The value stored in valueToDisplay$ always corresponds to 'model'. Despite trying various approaches to properly project the state, it s ...

Correctly inputting the 'in' statement - Avoid using a primitive value on the right side of an 'in' statement

I am currently facing an issue with my React code where I am getting the error message: The right-hand side of an 'in' expression must not be a primitive.. I am unsure about how to resolve this problem effectively: // The goal is to allow nu ...

The 'subscribe' property is not available on the type '() => Observable<any>'

File for providing service: import { Observable } from 'rxjs/Rx'; import { Http, Response} from '@angular/http'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/Map'; @Injectable() export clas ...

Utilizing data from the home component in another component: A guide

Here is the code I am working with, showcasing how to utilize (this.categoryType) in another component: getCategoryDetails(){ return this.http.get('ip/ramu/api/api/…') .map((res:Response) => res.json()); } The above code snippet is utilize ...

Ways to activate auto completion without using a string

Can anyone assist us with the tinymce editor? We have implemented an auto completion feature using a plugin from TinyMCE's documentation, but we are having trouble changing the triggering behavior. Currently, it only suggests options when "@" is typed ...

Utilizing TypeScript for dynamic invocation of chalk

In my TypeScript code, I am trying to dynamically call the chalk method. Here is an example of what I have: import chalk from 'chalk'; const color: string = "red"; const message: string = "My Title"; const light: boolean = fa ...

The attribute 'attribs' is not found on the 'Element' type in cheerio

When I run my code, I encounter an error that says Property 'attribs' does not exist on type 'Element'. It's puzzling to me why this error is being thrown. After examining the type definitions of cheerio, I discovered that attribs ...

Implementing a ReactJS component with a TypeScript interface for displaying an Alert box message using Material

I have a MUI Alert box in my application where I am trying to change the message inside with an href URL. However, when I use the herf tag, it shows as text instead of a link. How can I make it display as an actual link? In the code below, when I click th ...