在 Typescript 中导入私有接口

Import private interface in Typescript

这是一个例子。 localforage 包导出的所有内容都是私有 LocalForage class 的一个实例。各自的类型有一个同名的接口,但也没有导出。

尽管没有导出 LocalForage 接口,但 TypeScript 和 IDE (WebStorm) 似乎允许从“@types/localforage”导入它。但是类型没有应用。

此代码在 customForage.setDriver(...) 行之前没有 linting 问题和导入错误:

import * as localForage from 'localforage';
import { LocalForage } from '@types/localforage';

var customForage: LocalForage = localForage;
customForage.setDriver('custom');

但导致错误:

Unresolved function or method setDriver()

虽然这段代码

import * as localForage from 'localforage';

/// <reference path="../../../node_modules/@types/localforage/index.d.ts"/>

var customForage: LocalForage = localForage;
customForage.setDriver('custom');

成功识别 setDriver 方法。

@types终于到了,我很高兴,index.d.ts维护相对路径很麻烦。

在使用该接口的文件中,如果没有 <reference path="../../... /> 可以处理这种情况吗?

问题不限于特定的localforage包,但它是问题的一个很好的例子。

根据我阅读的内容和我使用@types 的日常工作,您永远不需要导入或引用@types。 @types 自动按名称解析。所以对于模块 localforage,@types localforage 被加载。 此处提供了简短摘要:https://blogs.msdn.microsoft.com/typescript/2016/06/15/the-future-of-declaration-files/

我猜想使用 webstorm 或 phpstrom 时的问题可能是您没有使用 typescript 的内置版本,而不是您为项目安装的版本。尝试使用自定义打字稿版本并加载您在 node_modules 中安装的版本。并确保使用 TypeScript 2.0