TypeScript .d.ts语法 - 导出和声明

10

我希望你能帮助我理解创建 .d.ts 文件的正确方式。

有些人使用以下语法,让我感到困惑:

// lib-a.d.ts
namespace My.Foo.Bar {
  interface IFoo {}
  interface IBar {}
}

对比。

// lib-b.d.ts
declare namespace My.Foo.Bar {
  interface IFoo {}
  interface IBar {}
}

对比。

// lib-c.d.ts
namespace My.Foo.Bar {
  export interface IFoo {}
  export interface IBar {}
}

对比。

// lib-d.d.ts
declare namespace My.Foo.Bar {
  export interface IFoo {}
  export interface IBar {}
}

对比。

// lib-e.d.ts
declare module My.Foo.Bar {
  export interface IFoo {}
  export interface IBar {}
}

哪一个是正确的?declare 有什么用?export 有什么用?何时使用 namespace 和 module?

1个回答

3
正确的方式是:
declare namespace NS {
    interface InterfaceTest {
        myProp: string;
    }

    class Test implements InterfaceTest {
        myProp: string;
        myFunction(): string;
    }
}

您可以通过编写一些 .ts 文件并使用 --declaration 选项进行编译(tsc test.ts --declaration),来检查正确的签名。这将生成一个带有正确类型的 d.ts 文件。

例如,上面的声明文件是从以下代码生成的:

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;
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接