gpt4 book ai didi

typescript - 在 Typescript 中,为什么 JSX.IntrinsicElements 不能像文档描述的那样工作?

转载 作者:行者123 更新时间:2023-12-02 14:50:47 27 4
gpt4 key购买 nike

我正在尝试在服务器端使用 JSX,而不使用 React。我正在关注有关 JSX 的 typescript 文档 here , 并在 .tsx 中写下以下内容文件。

declare namespace JSX {
interface IntrinsicElements {
foo: any
}
}
let elt1 = <foo/>
let elt2 = <bar/>

链接文档说:

In the above example, <foo/> will work fine but <bar/> will result in an error ...

但对我来说,它们都会导致相同的错误:

Property 'foo' does not exist on type 'JSX.IntrinsicElements'.
Property 'bar' does not exist on type 'JSX.IntrinsicElements'.

最佳答案

你需要module augmentation .我从here得到了答案.试试这个:

import React from "react";

declare module "react" {
namespace JSX {
interface IntrinsicElements {
foo: any
}
}
}

let elt1 = <foo/>
let elt2 = <bar/>

Demo

您的代码不起作用的原因是因为 JSX.IntrinsicElements 取自 @types/react 并且重新声明命名空间不起作用。您还会注意到,如果您不导入 react ( demo ),您的代码将正常工作。模块扩充基本上扩展了 @types/react 类型。

关于typescript - 在 Typescript 中,为什么 JSX.IntrinsicElements 不能像文档描述的那样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55834987/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com