When exporting an enum in StencilJS with TypeScript, the error "Cannot find name..." may occur

Looking for a solution:

https://github.com/napolev/stencil-cannot-find-name

In this project, there are two main files to consider:

custom-container.tsx

import { Component, Element, State } from '@stencil/core';

@Component({
    tag: 'custom-container',
    styleUrl: 'custom-container.scss',
})
export class WebComponent {
    @Element() el!: HTMLStencilElement;
    @State() label: String = '<empty>';
    componentDidLoad() {
        document.querySelector('.button_get_anchor').addEventListener('click', () => {
            let position = '<unset>';
            position = this.el.querySelector('custom-details').getDefaultKnobEPosition();
            this.label = position;
        });
    }
    render() {
        return [
            <div class="label">{this.label}</div>,
            <custom-details></custom-details>,
            <div>
                <button class="button_get_anchor">Get Anchor</button>
            </div>
        ];
    }
}

custom-details.tsx

import { Component, Method } from '@stencil/core';

@Component({
    tag: 'custom-details',
    styleUrl: 'custom-details.scss',
})
export class WebComponent {
    render() {
        return [
            <div class="details">This is the "custom-details"</div>
        ];
    }
    @Method()
    sayHelloWorldOnConsole() {
        console.log('Hello World!');
    }
    
    @Method()
    getDefaultKnobEPosition(): Anchor {
        return Anchor.Left;
    }
    
}
export enum Anchor {
    Left = 'left',
    Center = 'center',
    Right = 'right',
}

The Issue: After running $ npm start --es5, an error occurs regarding the 'Anchor' name not being found.

[ ERROR ]  TypeScript: ./stencil-cannot-find-name/src/components.d.ts:66:39
           Cannot find name 'Anchor'.
...

You can see the error in this image:

https://i.stack.imgur.com/2iWZN.png

Moreover, Visual Studio Code also highlights this issue as shown here:

https://i.stack.imgur.com/Wer7m.png

The problematic line can be viewed at:

https://github.com/napolev/stencil-cannot-find-name/blob/master/src/components.d.ts#L66

This file is auto-generated and cannot be modified directly. Any suggestions on resolving this?

Thanks!

Answer №1

Separating the Anchor enum into its own file successfully resolves the building issue:

/src/components/custom-elements/Anchor.ts

export enum Anchor {
    Start = 'start',
    Middle = 'middle',
    End = 'end',
}

/src/components/custom-elements/custom-elements.tsx

import { Component, Method } from '@stencil/core';
import { Anchor } from './Anchor';

@Component({
    tag: 'custom-elements',
    styleUrl: 'custom-elements.scss',
})
export class WebComponent {
    render() {
        return [
            <div class="elements">This is the "custom-elements"</div>
        ];
    }
    @Method()
    sayHelloWorldOnConsole() {
        console.log('Greetings Earthlings!');
    }
    //*
    @Method()
    getDefaultPosition(): Anchor {
        return Anchor.Start;
    }
    //*/
}

Answer №2

When dealing with an automatically generated file, your options may be limited. The components.d.ts file can only be properly typechecked if it has access to the Anchor type through importation.

import {Anchor} from './custom-details';

If necessary, you can inject the Anchor type into the global scope to ensure visibility for all files in your compilation context.

custom-details.tsx

export class WebComponent {
   // ....
}

declare global {
  enum Anchor {
    Left = 'left',
    Center = 'center',
    Right = 'right'
  }
}

(<{Anchor: typeof Anchor}>window.Stencil).Anchor = {
  Left = 'left',
  Center = 'center',
  Right = 'right'
};

However, resorting to this method is strongly advised against.

This approach introduces a type and, even worse, a value into the global namespace!

If facing this issue, it is recommended to report it as a bug.

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

The onchange functionality is not functioning as expected

I've added an onchange event to the select box, but it doesn't seem to be working. Any suggestions would be greatly appreciated. Thank you in advance. HTML [<select id="notifyBy" ng-change="selectchange()" style="border:none" class="formtex ...

Tips for stopping execution in Discord.js if the user no longer exists?

I'm currently working on a discord bot and encountered a minor issue. I am using "messageReactionRemove" and "messageReactionAdd" to manage certain roles by removing or adding them, but the problem arises when a user leaves the server. When this happe ...

Exploring JSON and jQuery to Address Filtering Challenges

Excuse the interruption, but I need some assistance with my filters. Below is the code I'm currently working on; however, none of my attempts have been implemented yet (the dropdown menu and checkboxes remain non-functional) to make it easier for you ...

Using Typescript literal types as keys in an indexer is a common practice

Can we create a TypeScript literal type that acts as a string key in an indexer? type TColorKey = 'dark' | 'light'; interface ColorMap { [period: TColorKey]: Color; } But when attempting this, the following error is generated: An ...

When a jQuery click event is triggered, the event.target will return the child element that was clicked within the

When I have a jQuery click event assigned to a hyperlink that contains an image, each with separate ids, I expect clicking the hyperlink to trigger the code event.target.id, returning the hyperlink's id. However, it actually returns the image's i ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Leveraging TypeScript to sort and extract specific elements from two arrays

Given two arrays, I am looking to identify the elements in array2 that match elements in array1 based on a specific property. The arrays are structured as follows: var array1 = [ {"myId": 1, "text": "a"}, {"myId& ...

The most recent npm version is experiencing functionality issues on Linux systems

After updating npm to the latest version, I encountered some issues on my Linux system. When attempting to install new modules, I received the following errors: Cannot find module 'asynckit' Cannot find module 'reflect-metadata' Canno ...

Having trouble downloading the Chip component in Material-UI? Learn how to fix the download issue

I used the UI to upload a file, and now I want to download it either after some time or instantly. I tried implementing this using the <Chip> component, but it's not working. I need assistance in resolving this issue. Uploaded File: const data ...

Using React with Typescript and ie18next to fetch translations from an external API

In the past, I have experience working with i18next to load translations from static json files. However, for my current project, I need to load all translations from an API. How can I achieve this? Additionally, how can I implement changing the translat ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...

Locate Vue Components That Are Persisting

After loading my app and immediately taking a Chrome memory heap snapshot, I found the following results. https://i.stack.imgur.com/QB8u3.png Upon further exploration of my web app and then returning to the initial loaded page to take another memory heap ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

Tips on avoiding scrolling when toggling the mobile navigation bar:

While working on a website using HTML, CSS, and BS3, I have created a basic mobile navigation. However, I am facing an issue where I want to disable scrolling of the body when toggling the hamburger button. The problem arises when the menu is toggled on, ...

Configuring Google Chart LineChart settings by utilizing the series attribute

I am looking to modify the options for my line chart. However, when I define the options as shown below, the first series setting gets ignored and only the second series property is applied. var options = { title: 'Temperature Graph ( sampling ev ...

Utilizing TypedPropertyDescriptor to limit decorators in Typescript when using decorator factories

When it comes to restricting what a decorator can apply on, the standard method involves using a TypedPropertyDescriptor like so: export function decorator(target, key, TypedPropertyDescriptor<T extends ...>) {...} While this approach works well whe ...

Is it possible for prettier to substitute var with let?

One of the tools I utilize to automatically format my Typescript code is prettier. My goal is to find out if there is a way to have prettier replace all instances of 'var' with 'let' during the formatting process. Below is the script I ...

Utilizing React JS to Embed PDF Page Numbers in an Iframe: A Step-by-Step

How can I use reactjs to include pageno in an iframe? // If 'image' is available, show another iframe which allows setting the page number. <Iframe className="iframes" url={`${image}?page=2`} // Change '2' t ...

Loading a gallery dynamically using AJAX in a CakePHP application

I am currently working with Cakephp 2.8.0 and I am facing an issue with implementing ajax in my application. I have a list of categories displayed as li links, and upon clicking on a category, I need to remove certain html code, locate the necessary catego ...

What is the best way to recycle Vue and Vuetify code?

<script> export default { data () { return { my_alert: false, text: '', color: 'success' } }, methods: { openAlt (text, color) { this.text = text this.color = color this.my_ale ...