declare 关键字
declare
关键字用于声明某个类型是存在的,这样编译器就不会报错。
typescript
a = 1 // 报错 a 未定义
typescript
declare let a: number
a = 1 // ✅
declare 关键字可以描述以下类型。
- 变量(const、let、var 命令声明)
- type 或者 interface 命令声明的类型
- class
- enum
- 函数(function)
- 模块(module)
- 命名空间(namespace)
注意:declare
关键字只能用于声明类型,不能用于定义实现。
全局 declare
全局 declare 用于声明全局变量,可用于JavaScript 引擎的原生对象添加属性和方法,。
typescript
export {};
declare global {
interface String {
toSmallString(): string;
}
}
String.prototype.toSmallString = ():string => {
// 具体实现
return '';
};
模块内 declare
我们可以为每个模块脚本,定义一个.d.ts文件,把该脚本用到的类型定义都放在这个文件里面。但是,更方便的做法是为整个项目,定义一个大的.d.ts文件,在这个文件里面使用declare module定义每个模块脚本的类型。
下面的示例是node.d.ts文件的一部分。
typescript
declare module "url" {
export interface Url {
protocol?: string;
hostname?: string;
pathname?: string;
}
export function parse(
urlStr: string,
parseQueryString?,
slashesDenoteHost?
): Url;
}
declare module "path" {
export function normalize(p: string): string;
export function join(...paths: any[]): string;
export var sep: string;
}
上面示例中,url
和path
都是单独的模块脚本,但是它们的类型都定义在node.d.ts
这个文件里面。
另一种情况是,使用declare module
命令,为模块名指定加载路径。
typescript
declare module "lodash" {
export * from "../../dependencies/lodash";
export default from "../../dependencies/lodash";
}
上面示例中,declare module "lodash" 为模块
lodash`,指定具体的加载路径。
使用时,自己的脚本使用三斜杠命令,加载这个类型声明文件。
typescript
/// <reference path="node.d.ts" />