typescript - typescript 导出类型和模块值
问题描述
我想导出一个与值同名的类型。这是一个示例模块:
// foo.ts
export type Foo = string;
export function create(): Foo {
// ...
}
这种模式起作用的原因是什么:
// index.ts
import * as _Foo from "./foo";
export const Foo = _Foo;
export type Foo = _Foo.Foo;
但这些模式没有?
// No compiler error but value is not exported
export type Foo = import("./foo").Foo;
export * as Foo from "./foo";
// Duplicate identifier error
import type { Foo } from "./foo";
import * as Foo from "./foo";
export { Foo };
// Individual declarations in merged declaration 'Foo' must be all exported or all local. [2395]
import * as Foo from "./foo";
export { Foo };
export type Foo = Foo.Foo;
解决方案
类型别名不会产生值。
让我解释一下你的例子中发生了什么
// Types (Foo) and values (create) are imported into a single variable
import * as _Foo from "./foo";
// The module is reexported with another name
export const Foo = _Foo;
// The type is reexported with another name
export type Foo = _Foo.Foo;
编译版不包含课程类型
var _Foo = require("./foo");
exports.Foo = _Foo;
之后, ifFoo
用作类型,它被正确解析为string
,但 ifFoo
用作值,它是一个带有create
字段的对象。
有趣的事实是你typeof Foo
现在可以使用它{ create: () => string }
继续前进 下面的内容与之前的内容非常相似,但由于第一次导入明确声明它是一种类型,因此可以对值导出使用相同的名称
export type Foo = import("./foo").Foo; // does not produce a variable
export * as Foo from "./foo"; // named value export
编译成
exports.Foo = require("./foo");
下一个有点棘手,说实话,我不知道为什么它不起作用。我想这可能是一个错误,因为import type
它是一个闪亮的新功能,但我还没有找到它。
import type { Foo } from "./foo";
import * as Foo from "./foo";
export { Foo };
本地定义的类型有效:
type Foo = string;
import * as Foo from "./foo";
export { Foo };
最后一个,因为Foo
在这个导入中声明的不能与它合并。您可以查看此问题以获取详细信息。
import * as Foo from "./foo";
export { Foo };
export type Foo = Foo.Foo; // <- local definition
它可以使用临时标识符重写,就像您在第一个示例中所做的那样:(它不起作用,请参阅下面的更新)
import * as _Foo from './Foo'
export { _Foo as Foo }
export type Foo = _Foo.Foo
更新
最后列出的片段会产生正确的 js 输出,但在将导出用作值时会引发错误:
import * as _Foo from './merged'
const x: Foo = '1234'; // Ok
const y = Foo.create(); // <- TS2693: 'Foo' only refers to a type, but is being used as a value here.
这似乎是一个错误,但我找不到它已发布
推荐阅读
- reactjs - 退出并重新打开应用程序后如何重新渲染页面?
- r - 无法打开 R/Cape 包
- sql-server - 何时生成“in”语句的案例
- javafx - 清除 TextField JavaFX 的内容
- swagger-codegen - 生成 Java 时 Swagger 将“on”映射为“true”
- generics - Refator 代码,用 Kotlin 编写成更具功能性的方式
- php - 我可以在非 Symfony 项目中使用 Symfony 的 Route Annotation
- terraform - 如何获得当前导演的相对路径到任意父目录?
- python - 注释 django 字段
- highcharts - HighCharts - 不要在最大值上裁剪系列线