登录/注册
小开开
2649
占位
2
占位
0
浏览量
占位
粉丝
占位
关注
TypeScript-外部声明
小开开
2020-12-06 17:18:32 2020-12-06
186
0

外部声明

外部声明一般针对第三方来历不明的库,当你想要在你的typescript项目中使用用javascript代码写的第三方库时,就需要用到外部声明。一个常见的例子,假设我们在HTML中通过script标签引入了全局jQuery:

// 注册全局变量 $
<script src="path/to/jquery.js"></script>

path/to/jquery.js 文件在会在全局作用域中引入对象 $,接下来如果在同一项目下的TypeScript文件中使用 $,TypeScript编译器会报错:

// 错误,缺少名字 $ 的声明信息
// error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try `npm i @types/jquery`
$('body').html('hello world');

由于没有任何类型信息,TypeScript编译器根本不知道 $ 代表的是什么,此时需要引入外部声明(因为$是外部JavaScript引入TypeScript代码中的)。外部声明的关键字是:

declare 

分析语句 $('body').html('hello world'); 得出:

  • $是一个函数,接收字符串参数
  • $调用返回值是一个对象,此对象拥有成员函数 html,这个成员函数的参数也是字符串类型
// 声明 $ 的类型信息
declare let $: (selector: string) => {
html: (content: string) => void;
};
// 正确,$已经通过外部声明
$('body').html('hello world');

声明应该是纯粹对于一个标识符类型或外观的描述,便于编译器识别,外部声明具有以下特点:

  • 必须使用 declare 修饰外部声明
  • 不能包含实现或初始化信息(内部声明可以在声明的时候包含实现或初始化)
// 声明a为一个数字
declare let a: number;
// 错误,外部声明不能初始化
// error TS1039: Initializers are not allowed in ambient contexts
declare let b: number = 2;
// 声明T为一个接口
declare interface T {}
// 声明接口类型变量b
let b: T;
// 声明fn为一个函数
// 错误,声明包含了函数实现
// error TS1183: An implementation cannot be declared in ambient contexts
declare function fn(){}
// 正确,不包含函数体实现
declare function fn(): void;
// 声明myFunc为一个函数
declare let myFunc: (a: number) => void;
// 声明MyEnum枚举类型
declare enum MyEnum {
A, B
}
// 声明NS为命名空间
declare namespace NS {
// 错误,声明不能初始化
// error TS1039: Initializers are not allowed in ambient contexts
const a: number = 1;
// 正确,仅包含声明
const b: number;
// 正确,函数未包含函数体实现
function c(): void;
}
// 声明一个类
declare class Greeter {
constructor(greeting: string);
greeting: string;
showGreeting(): void;
}

外部声明还可以用于声明一个模块,如果一个外部模块的成员要被外部访问,模块成员应该用 export 声明导出:

declare module 'io' {
export function read(file: string): string;
export function write(file: string, data: string): void;
}
暂无评论