TypeScript .d.ts语法-导出并声明 [英] TypeScript .d.ts syntax - export and declare

查看:1926
本文介绍了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;
        }
    }
}

这篇关于TypeScript .d.ts语法-导出并声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆