699 TypeScript其他知识:namespace,内置类型声明,外部定义类型声明和自定义声明,declare文件,tsconfig.json

模块化开发


命名空间namespace


类型的查找


内置类型声明


外部定义类型声明和自定义声明


声明变量-函数-类


声明模块


declare文件



tsconfig.json文件


tsconfig.json文件


目录结构


index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
  <script>
    let whyName = "hahaha"
    let whyAge = 18
    let whyHeight = 1.88

    function whyFoo() {
      console.log("whyFoo")
    }

    function Person(name, age) {
      this.name = name
      this.age = age
    }
  </script>

</body>
</html>

jie.d.ts

// 声明模块
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 { add, sub } from './utils/math'
import { time, price } from './utils/format'

import nhltImage from './img/nhlt.jpg'

// import axios from 'axios'
import lodash from 'lodash'

console.log(add(20, 30))
console.log(sub(20, 30))

console.log(time.format('11111111'))
console.log(price.format(123))

console.log(lodash.join(['abc', 'cba']))

// axios.get("http://123.207.32.32:8000/home/multidata").then(res => {
//   console.log(res)
// })

// document.getElementById

console.log(whyName)
console.log(whyAge)
console.log(whyHeight)

whyFoo()

const p = new Person('why', 18)
console.log(p)

$.ajax({})

format.ts

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'
  }
}

math.ts

export function add(num1: number, num2: number) {
  return num1 + num2
}

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

原文地址:https://www.cnblogs.com/jianjie/p/15081214.html