3.TypeScript声明文件

1 .ts

即可包含类型信息,也可以执行代码

//类型
type TypeA = {name: 'string'; age: number}
let PorpsA: TypeA = {
    name: 'Tom',
    age: 16
}
console.log(PorpsA.name)

2 .d.ts

只能包含类型信息,不可执行代码

type TypeB = {name: 'string'; age: number}

// 错误代码
//let PorpsB: TypeB = {
//    name: 'Tom',
//    age: 16
//}
//console.log(PorpsA.name)

3 TypeScript第三方类型声明库

//1. 自带类型声明文件
// axios库

//2.由DefinitelyTyped提供
//安装声明文件
npm i -D @types/*

4 创建声明文件:共享文件

index.d.ts

type Prop = {age: number}

a.ts

import { Prop } from './index'

b.ts

import { Prop } from './index'

declare为已有的.js文件提供声明类型,而不是创建一个新的变量,和.js文件相同时不需要导入
declare.ts

declare let conunt: number

interface Point {
    x: number
    y: number
}
declare let position: Point

declare function add {x: number, y: number}: number

declare function changeDirection (
    direction: 'up' | 'down'
): void

type FomartPoint = (point: Point) => void
declare const fomartPoint: FomartPoint
// 导出
export { count, position, add, changeDirection, fomartPoint, Point  }

declare.js

let conunt = 18

let position = {
    x: 0,
    y: 0
}

function add(x, y) {
  return x + y
}

function changeDirection(direction) {
  console.log(direction)
}

const fomartPoint = point => {
    console.log('坐标:', point)
}

// 导出
export { count, position}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容