Use Typescript declaration types inline

Viewed 462

After installing types for a library such as "@types/openlayers" how can I then use these for inline type definitions for things like 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;
   ...
}
1 Answers

Use it from the actual package that is being typed, not the @types/* module. For example, with react-router, you add @types/react-router but to pull out the RouteProps interface, you use import {RouteProps} from "react-router";.


Additionally, from your edits, it seems that you may be using the wrong @types/* package. You mention using @types/openlayers but then mention that you are using the package ol, which should probably use the @types/ol package for types.

Note 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/

After running yarn add ol @types/ol (or npm i ol @types/ol)

This seems to be using the right types:

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;
   ...
}
Related