【问题标题】:TypeScript .d.ts syntax - export and declareTypeScript .d.ts 语法 - 导出和声明
【发布时间】:2017-05-31 23:17:47
【问题描述】:

我需要帮助以了解创建 .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 {}
}

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

【问题讨论】:

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


    【解决方案1】:

    正确的做法是:

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

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 2020-11-22
      • 2022-01-15
      • 2022-10-30
      • 2020-12-24
      • 2015-11-22
      • 2018-09-23
      • 2016-12-06
      • 1970-01-01
      相关资源
      最近更新 更多