TypeScript基本知识(5)

58 阅读1分钟

命名空间

// 命名空间的用法 嵌套 抽离 导出 简化 合并

// namespace 命名空间所有的变量以及方法必须要导出才能访问
namespace Person {
  export let name = "张三";
  export function sayHi() {
    console.log("你好1");
  }
}

// namespace 命名空间嵌套
namespace Person1 {
  export namespace Person2 {
    export let name = "李四";
    export function sayHi() {
      console.log("你好1");
    }
  }
}

// 合并
namespace Person3 {
  export let age = 18;
}
namespace Person3 {
  export let sex = '男';
}

console.log(Person3.age, Person3.sex);


// 应用场景  跨端开发
namespace ios {
  export const pushNotification = (msg: string) => {

  };
}

namespace android {
  export const pushNotification = (msg: string) => {

  };
}

模块解析

// test.ts
// 默认导出 导出的东西可以是任何类型 一个模块只能出现一个默认导出
export default 1

// 分别导出
export let x = 1
export let arr = [1,2,3]

import xxx, {x, arr} from './test'
import * as test from './test'

console.log(xxx,x,arr) // 1 1 [ 1, 2, 3 ]
console.log(test.default) // 1

// 动态引入 import 只能在最上层引用
import('./test').then(res => {
  console.log('动态引入', res) // 动态引入 { x: 1, arr: [ 1, 2, 3 ], default: 1 }
})