模板:将 `@Method` 添加到组件 1.为内置 Element 类型使用别名类型2.切换到HTMLElement3.在导入语句中使用别名

问题描述

我不能在这里提供太多信息(因为确实没有),但仅此:

突然之间,在向模板组件添加 @Method 函数

@Method()
async setMenuItems(items: Element[]): Promise<void> {
  // code here
} 

组件停止编译并出现以下错误 - 真的没有帮助 - 错误

[ ERROR ]  ./src/components/menu-content/menu-content.tsx:63:44
           build error

     L62:  @Method()
     L63:  async setMenuItems(elements: Element[]): Promise<void> {
     L64:    const unsupportedChildren = elements.filter(e => !this.isSupportedChild(e)).map(e => e.tagName);

[12:37.1]  build Failed in 7.02 s

注意事项

  • 错误消息中的返回类型 Promise<void> 以红色突出显示
  • 在此组件中还有其他 @Method 可以工作(即使具有相同的返回类型)。
  • “破碎的”@Method 在结构上与那些有效的相同。
  • TypeScript 编译器不会抱怨任何事情
  • 只有模板编译器失败

我已经试过了...

我记得我曾经遇到过这个错误,显然我以某种方式修复了它(或者没有,idk)。但如果我这样做了,我不记得是怎么做的了。

有没有人知道如何调试这个 - 甚至更好的修复?

解决方法

我想通了。我的组件的更完整版本是:

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

class MenuContent {
  @Element() element: MenuContentElement;

  @Method()
  setMenuItems(elements: Element[]): Promise<void> {
    // ------------------^^^^^^^
    // Element is meant to be the built-in browser interface for Element
    // but stencil thinks that this is the imported Element from '@stencil/core'!
  }
}

这里的确切问题是,模板编译器似乎假设 elements 参数是从 Element 导入的 @stencil/core 类型,这显然是错误的并导致了这个奇怪的无用错误。

可能的解决方案

1.为内置 Element 类型使用别名类型

// types.ts
export type DomElement = Element;

// menu-content.tsx
import { DomElement } from './types';
...
async setMenuItems(elements: DomElement[]): Promise<void> { ... }

2.切换到HTMLElement

注意:这只是合法的,当您不需要支持其他元素类型(例如 SVGElements)时!

async setMenuItems(elements: HTMLElement[]): Promise<void> { ... }

3.在导入语句中使用别名

请注意:当使用@stencil eslint 规则时,他们会抱怨您重命名的导入并说“不允许自己的类成员是公共的”。

import { Element as ElementDecorator} from '@stencil/core';

class MenuContent {
  // eslint will complain about that:
  // "Own class properties cannot be public."
  @ElementDecorator() element: HTMLMenuContentElement;
}