What is preventing TypeScript from recognizing enums in libraries?

Check out the TypeScript types defined for html-validator:

declare namespace HtmlValidator {

    // ...

    enum ValidationResultsOutputFormats {
        json = 'json',
        html = 'html',
        xhtml = 'xhtml',
        xml = 'xml',
        gnu = 'gnu',
        text = 'text'
    }

    interface OptionsForHtmlFileAsValidationTargetAndObjectAsResult extends OptionsForHtmlFileAsValidationTarget {
      format?: 'json';
    }

    interface OptionsForHtmlFileAsValidationTargetAndTextAsResults extends OptionsForHtmlFileAsValidationTarget {
      format: 'html' | 'xhtml' | 'xml' | 'gnu' | 'text';
    }

    interface OptionsForExternalUrlAsValidationTargetAndObjectAsResult extends OptionsForExternalUrlAsValidationTarget {
      format?: 'json';
    }

    interface OptionsForExternalUrlAsValidationTargetAndTextAsResults extends OptionsForHtmlFileAsValidationTarget {
      format: 'html' | 'xhtml' | 'xml' | 'gnu' | 'text';
    }
}

(🔗 Full Version)

I am exploring the use of ValidationResultsOutputFormats instead of string literals. However, both IDE and TypeScript do not provide alerts or errors for the following code:

import validateHtml, { ValidationResultsOutputFormats } from 'html-validator';


export default abstract class HtmlValidator {

  public static validateHtml(compiledHtmlFile: Vinyl): void {

    // ...

    validateHtml({
      data: compiledHtmlFile.contents.toString(),
      format: ValidationResultsOutputFormats.json
    }).then((validationResults: validateHtml.ParsedJsonAsValidationResults) => 
    {
        // ...
    });
  }
}

Unfortunately, as ValidationResultsOutputFormats is undefined, a JavaScript error occurs:

Cannot read property 'json' of undefined

(referring to

format: ValidationResultsOutputFormats.json
).

Is this a mistake on my part or possibly a bug in TypeScript?

P. S. Please provide solutions that do not involve hardcoded string literals.

Update: my tsconfig.json

{
  "compilerOptions": {

    "target": "es6",
    "strict": true,

    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,

    "lib": [
      "es2018"
    ],

    "baseUrl": "./",
    "paths": {}
  }
}

Answer â„–1

After successfully installing the @types/html-validator package using the command below:

npm install @types/html-validator --dev

You do not need to explicitly import the type from the library itself.

The namespace will automatically be accessible in the global scope.

Here are some tips:

  • To avoid naming conflicts, consider renaming your class as HtmlValidator.
  • Make references to HtmlValidator in the import statement.
import * as HtmlValidator from 'html-validator';


export default abstract class Validator {

  public static validateHtml(compiledHtmlFile: Vinyl): void {

    // ...

    validateHtml({
      data: compiledHtmlFile.contents.toString(),
      format: HtmlValidator.ValidationResultsOutputFormats.json
    }).then((validationResults: HtmlValidator.ParsedJsonAsValidationResults) => 
    {
        // ...
    });
  }
}

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

BarChart is failing to exhibit data in tooltips when using dynamic keys

Query Description Hello! I'm currently tackling an issue with a bar chart. Everything is working smoothly, except for the default tooltip, which appears blank when hovering over the bars. My chart utilizes dynamic keys for the legends, and they are f ...

transfer data between JavaScript and PHP

I have set up a dynamic table structure in my project: <form method="POST" action="recieve.php"> <table> <thead> <th>Value</th> <th>Action</th> </thead> <tbody> <tr> ...

Tips for customizing Material UI Tooltip styles

Is there a way to customize the appearance of the Material UI Tooltip title? I have noticed that by default, the tooltip displays with a black background and no text wrap on hover. Can the background color, text color, and other styles be modified? Wonde ...

When using Ionic 3 on an Android device, the keyboard is causing the tabs and app content to shift upwards

I'm currently working on an Ionic 3 app and encountering a problem. Whenever I click on the search function, the keyboard opens and pushes all the content of the app to the top. https://i.sstatic.net/GaPW8.png https://i.sstatic.net/7d6Fm.png Here i ...

Are you looking to use the 'any' type instead of the 'Object' type? Angular Services can help you with that

I encountered the following error message: Argument of type 'OperatorFunction<APISearch[], APISearch[]>' is not assignable to >parameter of type 'OperatorFunction<Object, APISearch[]>'. The 'Object' type is ...

Unusual symbols in angular variable found within an HTML document

Currently in my HTML, I have code like this: <li ng-repeat="favorite in favorites track by $index"> <a ng-href="javascript:void(0)" ng-click="changeSVG(favorite)"> <i class="fa fa-sitemap"></i>{{favorite}} </a> </l ...

Strategies for transferring data from JavaScript to Express for seamless integration as a default value

I am currently utilizing express, MongoDB for the database, and EJS. I am in the process of developing a form that allows users to submit a new article for a blog. The goal is for the website to redirect back to the page with the form fields populated if a ...

Dropdown box not displaying any choices

I developed a basic reusable component in the following way: Typescript (TS) import {Component, Input, OnInit} from '@angular/core'; import {FormControl} from '@angular/forms'; @Component({ selector: 'app-select', templa ...

Why is AngularJS $http response undefined?

My $http call in AngularJS is returning undefined when I try to access the data in my controller. What could be causing this issue? Despite using .then to handle promises, the data passed to the controller seems to become undefined. Can you help me figure ...

Data vanishing upon selection of a date or update of the month

I have implemented VanillaCalendar to display events on specific days. You can view the complete demo in the code snippet provided below or by visiting it on CodePen The functionality involves iterating through JSON data and adding a div element to days ...

jQuery command to display a div element when a button is clicked

Hey there, I'm trying to display a div element in jQuery mobile when the user touches the button. I have already created custom classes for both the button and div element but unfortunately, nothing seems to happen. Can anyone tell me which classes I ...

When echoing SESSION in PHP, the previous value is displayed

<script language="javascript"> function handleEmergency() { if(document.getElementById('emer').checked == true) { <?php $_SESSION['total2']= $_SESSION['total1'] ...

State management in React using hooks

Recently, I've been grappling with form validation while working on a signup form for my React app using Next.js. I've noticed that many sign up pages typically hide an "invalid" message until the user interacts with an input field. I attempted t ...

Issue with bootstrap 4 CDN not functioning on Windows 7 operating system

No matter what I do, the CDN for Bootstrap 4 just won't cooperate with Windows 7. Oddly enough, it works perfectly fine on Windows 8. Here is the CDN link that I'm using: <!doctype html> <html lang="en> <head> <!-- Req ...

Dealing with the prompt "Are you certain you wish to leave this page?" when closing the page

When using my web application, a JavaScript message pops up asking 'Are you sure you want to navigate away from this page?' when attempting to open a new page. I am aware that I can handle this message with the Selenium.getAlert() method (or some ...

Retrieve XML node through AJAX request

I am in need of using AJAX to retrieve values from XML nodes and then utilize those values within an existing JavaScript function. Here's a sample of the XML data: <cars> <car mfgdate="1 Jan 15" name="Ford" id="1"> <engine litre ...

Using the key from the parent ng-repeat to filter ng-repeat

Here is an example: <div class="row" ng-repeat="(key, value) in sections"> <h5>{{ value }}</h5> <ul> <li ng-repeat="item in $parent.items | filter: key">{{ item.name }} -- {{ item.section }}</li> < ...

What causes the delay in loading certain CSS and JS files?

My ASP.NET MVC5 application hosted on an IIS Server has a slow-loading login page, especially after clearing the browser history. The Developer Tools Network field indicates a problem with loading page contents such as css and js files. Can you provide gui ...

Pressing the F5 key will cause i18next to revert back to the original default

i18n.js import i18n from 'i18next'; import { initReactI18next } from 'react-i18next'; import enTranslation from '../locales/en.json'; import trTranslation from '../locales/tr.json'; import deTranslation from '.. ...

Using Javascript to Trigger Events on Selection

I have a unique situation: 1) One of my dropdown's choices features various car names. 2) Another dropdown has two options: When selecting each option in the second dropdown, the following should occur: a) Choose UserInput - This action will hide ...