繁体   English   中英

内联使用 Typescript 声明类型

[英]Use Typescript declaration types inline

在为诸如“@types/openlayers”之类的库安装类型后,我如何将它们用于诸如 React props 之类的内联类型定义:

import Map from "ol/Map";    
import { Map as MapTypes } from "@types/openlayers"; // Error: Cannot import type declaration files.

export type Props = {
    mapInstance: MapTypes;
}

export const OlMap: FunctionComponent<Props> = (props): JSX.Element => {
   const currentMap = props.mapInstance;
   ...
}

从正在输入的实际包中使用它,而不是@types/*模块。 例如,使用react-router ,您添加@types/react-router但要拉出RouteProps接口,您使用import {RouteProps} from "react-router"; .


此外,从您的编辑,似乎你可能使用了错误的@types/*包。 您提到使用@types/openlayers但随后提到您正在使用包ol ,它可能应该使用@types/ol包作为类型。

注意申报文件消耗

在大多数情况下,类型声明包应始终与npm上的包名称具有相同的名称,但以@types/为前缀

运行yarn add ol @types/ol (或npm i ol @types/ol

这似乎使用了正确的类型:

import MapTypes from "ol/Map"; // Note that I don't need "{}" or "as" here
// import {Map as MapTypes} from "ol"; or pull it out of the root export

export type Props = {
    mapInstance: MapTypes;
}

export const OlMap: FunctionComponent<Props> = (props): JSX.Element => {
   const currentMap = props.mapInstance;
   ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM