打字稿和谷歌AMP?类型“JSX.IntrinsicElements”上不存在属性“amp-img”

tan*_*aum 9 javascript typescript reactjs amp-html

我有一个运行快速服务器的节点项目,当在 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} ... />
};
Run Code Online (Sandbox Code Playgroud)

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

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

[ts] Property 'amp-img' does not exist on type 'JSX.IntrinsicElements'.
Run Code Online (Sandbox Code Playgroud)

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

tan*_*aum 21

所以在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;
	}
}
Run Code Online (Sandbox Code Playgroud)

像这样手动执行的唯一缺点是,如果 Amp 规范发生变化,您必须自己更新它。所以如果目前还有其他选择,请告诉我。

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

  • 这个答案解决了我必须添加 **'amp-accordion': any;** 谢谢@tannerbaum 的问题。:) (3认同)