内联使用 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
but then mention that you are using the package ol
, which should probably use the @types/ol
包。
备注declaration file consumption:
For the most part, type declaration packages should always have the
same name as the package name on npm
, but prefixed with @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;
...
}
为诸如“@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
but then mention that you are using the package ol
, which should probably use the @types/ol
包。
备注declaration file consumption:
For the most part, type declaration packages should always have the same name as the package name on
npm
, but prefixed with@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;
...
}