使用 TypeScript 在 Visual Studio 中使用来自其他 commonjs 模块的类型(接口)而无需导入该模块?
Use types (interfaces) from other commonjs modules in Visual Studio using TypeScript without having to import that module?
我正在尝试简单地使用来自其他 commonjs 模块的类型(接口)。我想知道是否有一种方法可以在每次只需要类型(无实现)时不必导入模块来执行此操作?
同样的道理。我如何在不使用“--module commonjs”编译的情况下在项目中使用 commonjs 声明的模块类型? (只是为了使用类型,我知道如果你不关心类型安全,你可以做 var x = require('x')
,但这违背了 TypeScript 的目的)
这似乎是一个有效的用例,因为人们可能希望创建一个不受实际实现影响的库...但正如我目前所看到的,您必须 import x = require('x')
实际实现,即使我不需要它并且已经有了定义文件。
有没有办法告诉编译器它"just exists,"类似于声明变量的方式?
示例:
假设我 file.ts 没有使用任何模块设置进行编译 (none):
/// <reference path="ExternalCommonJSModule.d.ts" />
export class A {
public foo(bar: ITypeFromExternalCommonJSModule): number {
return bar.x * 2;
}
}
假设 ExternalCommonJSModule.d.ts 看起来像这样:
declare module "ExternalCommonJSModule" {
export interface ITypeFromExternalCommonJSModule {
x: number;
}
}
(注意,这个 不会 编译,因为 file.ts 不是用 --module commonjs 编译的,它也不会导入 .d.ts)
I'm wondering if there is a way to do this without having to import the module each time I need just the types (no implementation)
您可以将接口放在全局模块中,例如globals.d.ts
这样您就可以在整个项目中使用它们而无需导入。
注意:一旦全球化,您就会严重限制代码的 可共享性 并使自己面临 钻石版本依赖性问题 .
我正在尝试简单地使用来自其他 commonjs 模块的类型(接口)。我想知道是否有一种方法可以在每次只需要类型(无实现)时不必导入模块来执行此操作?
同样的道理。我如何在不使用“--module commonjs”编译的情况下在项目中使用 commonjs 声明的模块类型? (只是为了使用类型,我知道如果你不关心类型安全,你可以做 var x = require('x')
,但这违背了 TypeScript 的目的)
这似乎是一个有效的用例,因为人们可能希望创建一个不受实际实现影响的库...但正如我目前所看到的,您必须 import x = require('x')
实际实现,即使我不需要它并且已经有了定义文件。
有没有办法告诉编译器它"just exists,"类似于声明变量的方式?
示例:
假设我 file.ts 没有使用任何模块设置进行编译 (none):
/// <reference path="ExternalCommonJSModule.d.ts" />
export class A {
public foo(bar: ITypeFromExternalCommonJSModule): number {
return bar.x * 2;
}
}
假设 ExternalCommonJSModule.d.ts 看起来像这样:
declare module "ExternalCommonJSModule" {
export interface ITypeFromExternalCommonJSModule {
x: number;
}
}
(注意,这个 不会 编译,因为 file.ts 不是用 --module commonjs 编译的,它也不会导入 .d.ts)
I'm wondering if there is a way to do this without having to import the module each time I need just the types (no implementation)
您可以将接口放在全局模块中,例如globals.d.ts
这样您就可以在整个项目中使用它们而无需导入。
注意:一旦全球化,您就会严重限制代码的 可共享性 并使自己面临 钻石版本依赖性问题 .