【问题标题】:How to add element type to JSX namespace in a separate package?如何在单独的包中将元素类型添加到 JSX 命名空间?
【发布时间】:2019-10-21 03:31:57
【问题描述】:

我正在为 Polymer 库创建一个带有 typescript 类型的包。这些类型将在 React 项目中使用,因此我需要将元素类型添加到 JSX.IntrinsicElements

import { HTMLAttributes } from "react";
import { PolymerElement } from '@polymer/polymer';

interface CoralTooltipAttributes<T> extends HTMLAttributes<T> {
    selector?: string;
    condition?: Function;
    renderer?: Function;
    position?: string;
    transitionStyle?: string;
}

interface CoralTooltipElement extends PolymerElement {}

declare namespace JSX {
    interface IntrinsicElements {
        "coral-tooltip": React.DetailedHTMLProps<CoralTooltipAttributes<CoralTooltipElement>, CoralTooltipElement>;
    }
}

我已将"types": "index" 添加到我的package.json。 问题是当我 npm 将此包与我的项目链接时,它只是看不到 "coral-tooltip" 并显示这样的错误

ButtonGroup.tsx(32,21): 错误 TS2339: 属性 'coral-tooltip' 确实 'JSX.IntrinsicElements' 类型上不存在。

我还在项目的 tsconfig.json 中添加了这个字符串:"types": [ "elf-typings" ]

我应该怎么做才能让 typescript 成功导入元素的类型?

【问题讨论】:

  • 可能您的打字文件没有被拾取。您是否尝试更改 tsconfig 中的 typeRoots?它应该设置为 'node_modules/types', 'node_modules/' 在你的情况下
  • 其实不太行。我必须在 .tsx 文件中添加 import 'my-package-with-types'; ,然后打字稿才能从包中找到类型。 package.json 中的 types 没有帮助。

标签: reactjs typescript


【解决方案1】:

正如 Doğancan Arabacı 提供的那样

您的打字文件可能没有被拾取。你有没有尝试改变 tsconfig 中的 typeRoots?它应该设置为“node_modules/types”, 'node_modules/' 在你的情况下

.tsx文件的顶部也必须插入这个字符串

/// <reference types="my-package-with-types" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-17
    • 2017-11-27
    • 1970-01-01
    • 2021-06-28
    • 2012-05-23
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多