模块与命名空间

Tutorial: TS初级二 Category: TS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
  1. TS 中的模块
// JS中的模块
/*
1.默认导入与导出
// 注意点: 这里导入和导出的名字, 可以不一致
export default xxx
import ooo from "路径"
*/

/* 
1.按需导入与导出
注意点: 这里导入和导出的名字必须一致
export xxx;
import {xxx} from "路径"
*/

// node中的模块
/* 
1.exports.xxx = xxx
const xxx = require("path");
const {xx, xx} = require("path");

2.module.exports.xxx = xxx
const xxx = require("path");
const {xx, xx} = require("path");
*/

// 3.TS中的模块
// 默认情况下在JS中是不兼容上面两种导入方式混合使用, 而TS中对他们做了综合
import Test = require("./moduleTest");

class UserInfo implements Test.IPerson {
  name = "高圆圆";
  age = 18;
  sex = "女";
  show() {
    console.log("你好");
  }
}

let u = new UserInfo();
console.log(u.name);
u.show();

import { obj } from "./moduleTest";
console.log(obj);
  1. TS 中的命名空间
namespace A {
  export const a = 10;
}

// console.log(A.a);

// 嵌套命名空间
namespace B {
  export const b = 200;
  export namespace C {
    export const c = 300;
  }
}

// console.log(B.b);
// console.log(B.C.b);

// 简化命名空间
import c = B.C.c;
console.log(c);

// 引入
import { D } from "./namespaceTest";
console.log(D.d);
  1. 三斜杠语法
/// <reference path="./namespaceTest2.ts" />

// const a: User.IName = {
//   uname:  "万茜"
// }

// console.log(a);

const a: User.UserInfo.IName = {
  uage: 18,
};

console.log(a);
  1. 声明合并
// 1.接口
// interface ITest {
//   name: string
// }

// interface ITest {
//   age: number
// }

// class Person implements ITest {
//   name: string = "文咏珊"
//   age: number = 18
// }

// let p = new Person()
// console.log(p.name, p.age);

// interface ITest {
//   show(value: number): number
// }

// interface ITest {
//   show(value: string): number
// }

// const func: ITest = {
//   show(value: any): number {
//     if(typeof value === "string") {
//       return value.length
//     }else {
//       return value.toFixed()
//     }
//   }
// }
// console.log(func.show("世界上最遥远的距离就是,你是if而我是else, 似乎一直相伴但又永远相离"));
// console.log(func.show("世界上最痴心的等待,是我当case而你当switch,或许永远都选不上自己"));
// console.log(func.show("世界上最真情的相依,是你在try我在catch.无论你发神马脾气,我都默默承受,静静处理.到那时,再来期待我们的finally"));
// console.log(func.show(3.14));

// 2.命名空间
// namespace A {
//   export let a = 10;
// }
// namespace A {
//   export let a = 100;
// }

// 命名空间与类合并
// class Person {
//   // prototype上面
//   say():void {
//     console.log("say 孙怡");

//   }
// }

// namespace Person {
//   export const hi = ():void => {
//     console.log("hi 孙怡");

//   }
// }

// console.dir(Person)

// 命名空间与函数合并
// 注意点: 函数里面可以使用命名空间定义的变量
// function getCounter() {
//   getCounter.count++;
//   console.log(getCounter.count);

// }

// namespace getCounter {
//   export let count: number = 0
// }

// getCounter()

// 命名空间与枚举合并
namespace Gender {
  export const money: number = 18;
}
enum Gender {
  Male,
  Female,
}

// { '0': 'Male', '1': 'Female', Male: 0, Female: 1, money: 18 }
console.log(Gender);
Prev: 装饰器 Next: None