TS(五)模块化

TS(五)模块化

TypeScript支持两种方式来控制我们的作用域:
在这里插入图片描述

  1. 模块化:每个文件可以是一个独立的模块,支持ES Module,也支持CommonJS
export function add(num1: number, num2: number) {
  return num1 + num2
}

export function sub(num1: number, num2: number) {
  return num1 - num2
}

  1. 命名空间:通过namespace来声明一个命名空间
export namespace time {
  export function format(time: string) {
    return "2222-02-22"
  }

  export function foo() {

  }

  export let name: string = "abc"
}

export namespace price {
  export function format(price: number) {
    return "99.99"
  }
}

使用命名空间内的函数

// 在main.ts中
import { time, price } from './utils/format'
console.log(time.format("11111111"))
console.log(price.format(123))

1、每个模块类型的查找

1. 内置类型声明

  • 内置类型声明是typescript自带的、帮助我们内置了JavaScript运行时的一些标准化API的声明文件
  • 包括比如Math、Date等内置类型,也包括DOM API,比如Window、Document等;
  • 内置类型声明通常在我们安装typescript的环境中会带有的
// 比如:
const imageEl = document.getElementById("image") as HTMLImageElement

2. 外部定义类型声明

  • 引用包的类型声明包:https://www.typescriptlang.org/dt/search?search=
    在这里插入图片描述
  1. 自己在.d.ts文件中定义的类型声明包
    在这里插入图片描述
    使用declare声明:格式如下:
 declare module '模块名' {}
// 声明模块
declare module 'lodash' {
  export function join(arr: any[]): void
}

// 声明变量/函数/类
declare let whyName: string
declare let whyAge: number
declare let whyHeight: number

declare function whyFoo(): void

declare class Person {
  name: string
  age: number
  constructor(name: string, age: number)
}

// 声明文件
declare module '*.jpg'
declare module '*.jpeg'
declare module '*.png'
declare module '*.svg'
declare module '*.gif'

// 声明命名空间
declare namespace $ {
  export function ajax(settings: any): any
}
  • 在main.ts中使用:
// 引入模块名就行了
import lodash from "lodash";
// 然后就可以正常使用
console.log(lodash.join(["abc", "cba"]));

console.log(whyName);
console.log(whyAge);
console.log(whyHeight);
whyFoo();
const p = new Person("why", 18);
console.log(p);

$.ajax({});
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值