从.d.ts文件中导出“混合”声明-Typescript
从.d.ts文件中导出“混合”声明-Typescript
我有一个Typescript项目,其中有一个.ts文件,导出了一些接口和一个类。\n类似于这样:\n
export interface Tree { value: string, anotherValue: number, children: Tree[] } export class Utils { static adder(val1: number, val2: number): number { return val1 + val2; } [...一些其他静态函数...] }
\n现在我构建了这个项目(使用基本的tsc命令 - ES2015模块作为目标),在我的/dist目录中会有一个.d.ts文件和一个.js文件。\n在.js文件中,当然不再有任何接口。所以它看起来像这样:\n
export class Utils { static adder(val1, val2) { return val1 + val2; } [...一些其他静态函数...] }
\n在.d.ts文件中,我有所有的接口和类的声明,像这样:\n
export interface Tree { value: string, anotherValue: number, children: Tree[] } export class Utils { static adder(val1: number, val2: number): number; }
\n到目前为止一切都很好 - 一切看起来都很棒。\n现在我将我的包(/dist文件夹)安装到另一个项目中,并且真的很想在那里使用我的接口。\n所以我做了这个:\n
import {Tree} from "myPackage/dist/myFile" const myTree: Tree = {someTreeObject}
\n但是Typescript会告诉我\"Cannot use namespace \'Tree\' as a type\" - 为什么是命名空间?\n另一种尝试:\n
import * as Stuff from "myPackage/dist/myFile" const myTree: Stuff.Tree = {someTreeObject}
\n但是Typescript会告诉我\"Namespace \'\"*\"\' has no exported member \'Tree\'.\"。\n然后我看了一些其他的Typescript声明,并想到\"也许你需要使用一个命名空间\"(错误信息也是这样),所以我将myFile改成了这样:\n
export declare namespace myFile { interface Tree { value: string, anotherValue: number, children: Tree[] } class Utils { static adder(val1: number, val2: number): number { return val1 + val2; } [...一些其他静态函数...] } }
\n试图使用
import {myFile} from "myPackage/dist/myFile"
,我又遇到了\"Namespace \'\"*\"\' has no exported member \'Tree\'.\"的错误。\n有谁能告诉我这里出了什么问题?我猜应该是很简单的问题,但是我就是不明白。\n这是一个复现仓库:\nhttps://github.com/schadenn/typescript-problem-repro
\n你可以自己运行npm run build
,也可以只是安装.tgz包然后尝试
import { NavUtils, TsUtils } from "@test/utils"
并使用
NavUtils.ITree
或
TsUtils.Omit
。\n我还将dist文件夹检入,以便您可以看到包的内容。\n谢谢。