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

时间:2017-01-17 01:55:02

标签: typescript visual-studio-2015 typescript-typings typescript1.8

我需要帮助才能了解创建.d.ts文件的正确方法。

让我觉得有些人使用这种语法:

// 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 {}
}

哪一个是正确的?什么是声明用于?什么是出口用于?何时使用命名空间与模块?

1 个答案:

答案 0 :(得分:2)

正确的方法是:

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