# 十九.扩展全局变量类型
前言
- .ts/.tsx 文件:可以使用 declare global
- .d.ts 文件:任何内容都会自动进入全局作用域,它还允许您将全局定义放在单独的文件中
- 单模块覆盖:declare const window
# 1.扩展局部变量
可以直接使用接口对已有的类型进行扩展
# 1.1 String 扩展
global.d.ts
定义全局类型
interface String {
double(): string
}
1
2
2
- 扩展原型方法
String.prototype.double = function () {
return (this as string) + this
}
1
2
3
2
3
- 使用
let str: string = "abc"
str.double()
1
2
2
# 1.2 window 扩展
global.d.ts
定义全局类型
interface Window {
myname: string
}
1
2
2
- 扩展属性
window.myname = "asdasdfasdfasd"
1
- 使用
console.log(window.myname)
1
# 2.模块内全局扩展
全局变量可以通过 declare global 声明
test.ts
declare global {
interface String {
double(): string
}
interface Window {
myname: string
}
var $NAME: string
}
globalThis.$NAME = "张三" //var $NAME: string 中必须是 var,不能是 const 或 let
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
"use strict";
globalThis.$NAME = "张三"; //var $NAME: string 中必须是 var,不能是 const 或 let
1
2
2
# 3.声明合并
同一名称的两个独立声明会被合并成一个单一声明,合并后的声明拥有原先两个声明的特性
# 1.同名接口合并
interface Animal {
name: string
}
interface Animal {
age: number
}
let animal: Animal = { name: "abcd", age: 10 }
1
2
3
4
5
6
7
2
3
4
5
6
7
"use strict";
let animal = { name: "abcd", age: 10 };
1
2
2
# 3.命名空间的合并
- 扩展类
class Form {}
namespace Form {
export const type = "form"
}
1
2
3
2
3
"use strict";
class Form {
}
(function (Form) {
Form.type = "form";
})(Form || (Form = {}));
1
2
3
4
5
6
2
3
4
5
6
- 扩展方法
function getName() {}
namespace getName {
export const type = "form"
}
1
2
3
2
3
"use strict";
function getName() { }
(function (getName) {
getName.type = "form";
})(getName || (getName = {}));
1
2
3
4
5
2
3
4
5
- 扩展枚举类型
enum Seasons {
Spring = "Spring",
Summer = "Summer",
}
namespace Seasons {
export let Autum = "Autum"
export let Winter = "Winter"
}
1
2
3
4
5
6
7
2
3
4
5
6
7
"use strict";
var Seasons;
(function (Seasons) {
Seasons["Spring"] = "Spring";
Seasons["Summer"] = "Summer";
})(Seasons || (Seasons = {}));
(function (Seasons) {
Seasons.Autum = "Autum";
Seasons.Winter = "Winter";
})(Seasons || (Seasons = {}));
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 3.交叉类型合并
import { createStore, Store } from "redux"
type StoreWithExt = Store & {
ext: string
}
let store: StoreWithExt
1
2
3
4
2
3
4
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let store;
1
2
3
2
3
# 4.生成声明文件
配置tsconfig.json
为 true 生成声明文件
"declaration": true
1
← 十八.类型声明