类型声明declare
1、概览
1.1 declare是什么
前提:假如现在有一门用Typescript写的库,想供其他开发人员使用,有两种方式
方式1 打包ts源文件(供ts用户使用)和编译后的js文件(供js用户使用)
方式2 提供编译后的js文件和供ts用户使用的类型声明
后一种方式的优点:所占文件体积较小,十分明确该导入声明,并省去ts进一步编译的时间
类型声明定义:
万事并不总是如意,代码也不一定都有静态类型
类型声明文件的拓展名为 .d.ts, 是为无类型的js代码附加ts类型的一种方式
举个栗子:
import {Subscribe} from './subscribe'
export declare class Observe impelement Subscribabel{
public_isScalar:boolean = false
constructor (subscribe?:string){
this.subscribe = subscribe
}
subscribe(observe?:paetialObserver):Subscription{
// xxxxx
}
}
/* 使用TSC编译,tsc -d Observabel.ts 将会i得到类型声明文件Observabel.d.ts,可以看到,只保留了类型,没有值,也没有任何函数的具体内容 */
import {Subscribe} from './subscribe'
export declare class Observe impelement Subscribabel{
_isScalar:boolean
constructor (subscribe?:string);
subscribe(observe?:paetialObserver):Subscription
}
1.2 declare的作用
1.2.1 外参变量声明
在ts当中,想要不加var关键字定义一个全局变量会触发报警,正确的做法是在文件中先向typescript声明,有一些全局变量process
declare let process :{
env : {
NODE_ENV :'production' | 'development'
}
}
process = {
env : {
NODE_ENV :'production'
}
}
1.2.2 外参模块声明
declare module '模块名'{
export type MyType = number
export default MyType
}
declare module '@mc/error-boundary'
//只不过使用时会缺失一些安全性
eg: import {x} from from '@mc/error-boundary'
x //an
import b from './test.json'
b // object