【问题标题】:Typescript and Google AMP? Property 'amp-img' does not exist on type 'JSX.IntrinsicElements'打字稿和谷歌 AMP? “JSX.IntrinsicElements”类型上不存在属性“amp-img”
【发布时间】:2018-11-08 04:52:43
【问题描述】:

我有一个运行 express 服务器的节点项目,当查询 url 中带有 /amp 的新闻文章时,返回该文章的 amp 版本。

由于客户的要求,这些 amp 文章是使用 React 组件构建的,这些组件最终呈现为静态标记。这是其中一个组件:

import * as React from 'react';
import { Article_modulesByArticleId_edges_node } from '../../data/__generated__/Article';

// GraphQL auto generated type for the data that is sent to this component 
type Props = {
	module: Article_modulesByArticleId_edges_node;
};

export default (props: Props) => {
	const image = props.module.image;
	if (!image || !image.url || !image.title || !image.copyright) {
		return "";
	}

	return <amp-img alt={image.title} src={image.url} ... />
};

问题?该项目还使用我不太熟悉的打字稿。

当我尝试使用自定义 AMP-HTML 元素时,打字稿会抛出以下错误消息:

[ts] Property 'amp-img' does not exist on type 'JSX.IntrinsicElements'.

我找不到任何定义了 AMP 类型的节点包,而且总体上没有太多关于 Typescript 和 AMP 的讨论。有没有人有什么建议?我必须为 AMP 元素编写自己的声明吗?

【问题讨论】:

  • 这里有一个github post 讨论如何在全球范围内讨论自定义标签。我认为这个解决方案可以帮助您解决问题。

标签: javascript reactjs typescript amp-html


【解决方案1】:

所以在前面的 AMP 元素的编写声明中,还不错。共有三个选项:

// Any element you create will be accepted
declare namespace JSX {
	interface IntrinsicElements {
		[elemName: string]: any;
	}
}

// The elements you list here will be accepted, attributes don't matter
declare namespace JSX {
	interface IntrinsicElements {
		'amp-img': any;
	}
}

// The elements you list here will be accepted, and only with the attributes that you include here
declare namespace JSX {
	interface AmpImg {
		alt?: string;
		src?: string;
		width?: string;
		height?: string;
		layout?: string;
	}
	interface IntrinsicElements {
		'amp-img': AmpImg;
	}
}

像这样手动操作的唯一缺点是,如果 Amp 规范发生变化,您必须自己更新它。所以让我知道目前是否有其他选择。

无论如何,希望这对某人有所帮助!

【讨论】:

  • github.com/ampproject/amp-toolbox/tree/master/packages/… 是机器可读格式模式的官方来源。
  • 这个答案解决了我必须添加的问题 'amp-accordion': any; 感谢@tannerbaum。 :)
  • 第一个选项对我不起作用,我认为这是因为命名元素比[element: string]具有更高的特异性。
【解决方案2】:

在页面内,@tannerbaum 给出的答案对我不起作用,因为似乎没有使用命名空间。

相反,这对我有用:

declare global {
  namespace JSX {
    interface IntrinsicElements {
      [elemName: string]: any;
    }
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-21
    • 2017-03-02
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2019-02-18
    相关资源
    最近更新 更多