declare 声明 常见用法

原帖

declare 就是告诉 TS 编译器你担保这些变量和模块存在,并声明了相应类型,编译的时候不需要提示错误

1.declare 如同 interface、type 关键词一样,在编译成 js 之后是会被删除的。 declare 声明的是一个变量

// 例子 1:

1
2
3
4
5
6
7
8
#index.html
<script>
var myMap = new Map();
</script>
<script src="./index.js"/>

#index.ts
myMap.set('key', 'value');

当你在 index.ts 中直接调用 myMap 的时候是会报错的,因为 TS 找不到 myMap 这个变量。如果用 const 或者 let 声明,

又会导致变量被覆盖,那么解决办法就是用 declare。

#index.ts

1
2
3
declare;
myMap: Map<string, string>; // 声明在运行上下文之中存在一个叫做 myMap 的变量
myMap.set("key", "value");

2.declare module xxx {} 是用来做一些第三方库没有支持 ts 的,通过 declare module,让我们在代码中可以 import 进来,从而使用它

// 一般来说这个 .d.ts 文件会被放在工程的更目录下,如:

  • xxx.d.ts
1
2
3
4
5
6
7
8
9
10
11
export var value: number;
export function hello(str: string): String;
}
declare var D2: string;
declare namespace mySpace {
interface ITest {
id: number;
}
}

declare module "test" {}

// 这样子我们在文件中 import 那个没有支持 ts 的库就不会报错了,而且还会提示 库暴露出来的属性/方法

1
2
3
4
5
6
import test from "test";

test.hello("123");
test.value;
window.D2 = "hello";
const obj: mySpace.ITest = { id: 1 };

// 上面的例子只有 declare module 才是定义一个模块,才能被 import,其他的用法如上

3.模块扩展

// 1.ts

1
2
3
4
5
6
export class AClass {
public a: string;
constructor(a: string) {
this.a = a;
}
}

// 2.ts

1
2
3
4
5
6
7
8
9
import { AClass } from "./1";
declare module "./1" {
interface AClass {
test: (b: number) => number;
}
}
AClass.prototype.test = (b: number): number => {
return b;
};

4.全局扩展,在 **d.ts****文件中声明的都是全局扩展。**

// observable.ts

1
2
3
4
5
6
7
8
9
10
11
export class Observable<T> {
// ... still no implementation ...
}
declare global {
interface Array<T> {
toObservable(): Observable<T>;
}
}
Array.prototype.toObservable = function () {
// ...
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!