◆

TypeScript 命名空间 namespace 用法详解

2023-02-02 01:370

namespace 如何使用

首先定义一个 namespace

export namespace Test {
  const name = 'wfly';

  export const getName = () => {
    return name;
  };

  export const getAge = () => {
    return '18';
  };
}

console.log(Test.getName());
console.log(Test.getAge());

执行 tsc 编译此 ts 文件,编译后的代码如下

export var Test;
(function (Test) {
  const name = 'wfly';
  Test.getName = () => {
    return name;
  };
  Test.getAge = () => {
    return '18';
  };
})(Test || (Test = {}));
console.log(Test.getName());
console.log(Test.getAge());

可以看出定义的 namespace 是一个对象,在 namespace 中进行 export 导出的会作为对象的属性。

定义一个 html 引入编译后的 js 进行测试

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <script type="module" src="../dist/namespace.js"></script>
  </head>
</html>

可以发现最后输出 wfly 18

由上述示例,可以看出 typescript 当初定义 namespace 时是为了将一类代码分离,就像 ES6 的模块化一样,由于 ES6 有了模块化,这个基本就不会使用了

虽然 namespace 在应用模块化的概念中被 ES 模块替换,但是在 ts 中的类型定义还是有一部分作用的

用命名空间管理类型

如下定义了一个 Test 命名空间,然后定义了两个类型,从 Test 中可以去调用其中定义的类型

export namespace Test {
  export type Person = { name: string; age: number };

  export interface Props {
    name: string;
    age?: number;
  }
}

const person: Test.Person = {
  name: 'wf',
  age: 18,
};
const persons: Test.Props = { name: 'wf' };
💬留言板0

还没有留言,来发表第一条吧~

PAGE LOAD / LIVETypeScript 命名空间 namespace 用法详解加载中