TypeScript .d.ts语法-导出并声明
我需要帮助来了解什么是创建.d.ts文件的正确方法.
I need help trying to understand what is the correct way to create a .d.ts file.
让我震惊的是,有些人使用了这种语法:
What threw me is that some people use this syntax:
// lib-a.d.ts
namespace My.Foo.Bar {
interface IFoo {}
interface IBar {}
}
vs.
// lib-b.d.ts
declare namespace My.Foo.Bar {
interface IFoo {}
interface IBar {}
}
vs.
// lib-c.d.ts
namespace My.Foo.Bar {
export interface IFoo {}
export interface IBar {}
}
vs.
// lib-d.d.ts
declare namespace My.Foo.Bar {
export interface IFoo {}
export interface IBar {}
}
vs.
// lib-e.d.ts
declare module My.Foo.Bar {
export interface IFoo {}
export interface IBar {}
}
哪个是正确的?声明的用途是什么?出口有什么用?何时使用命名空间与模块?
Which one is correct? What is declare used for? What is export used for? When to use namespace vs. module?
正确的方法是:
declare namespace NS {
interface InterfaceTest {
myProp: string;
}
class Test implements InterfaceTest {
myProp: string;
myFunction(): string;
}
}
您始终可以通过写入一些.ts
文件并使用--declaration
选项(tsc test.ts --declaration
)对其进行编译来检查正确的签名.这将生成具有正确键入的d.ts
文件.
You always can check the correct signature by writing some .ts
file and compiling it with the --declaration
option (tsc test.ts --declaration
). This will generate a d.ts
file with the correct typings.
例如,上面的声明文件是从以下代码生成的:
For example the above declaration file was generated from the following code:
namespace NS {
export interface InterfaceTest {
myProp: string;
}
export class Test implements InterfaceTest {
public myProp: string = 'yay';
public myFunction() {
return this.myProp;
}
}
class PrivateTest implements InterfaceTest {
public myPrivateProp: string = 'yay';
public myPrivateFunction() {
return this.myProp;
}
}
}