TypeScript详解十七:类型扩展

1. 扩展局部变量类型

  • 拓展一个add方法,实现字符串拼接
interface String {
  add(value: string): string;
}
String.prototype.add = function (value: string) {
  return this + value;
}
let result = new String('hello').add(' word');
console.log(result); // hello word
  • 在Window上扩展一个变量
interface Window {
  userName: string;
}

在其他文件就可以拿到拓展的属性或者方法

在这里插入图片描述

2. 模块内全局扩展

注意:如果在扩展变量的文件加上了export {},导出为一个模块的话,此处要修改为以下代码:

  • declare global {} 的方式将模块内部扩展改为全局扩展
export { }
declare global {
  // 拓展一个add方法,实现字符串拼接
  interface String {
    add(value: string): string;
  }
  // 在Window上扩展一个变量类型
  interface Window {
    userName: string;
  }
}

String.prototype.add = function (value: string) {
  return this + value;
}
let result = new String('hello').add(' word');
console.log(result); // hello word

此时也可以在其他文件使用

在这里插入图片描述

3. 合并声明

  • 同一名称的两个独立声明,会被合并成一个单一声明
  • 合并后的声明拥有原来两个声明的特性
interface Person {
  name: string;
}
interface Person {
  age: number;
}
type P = Person;
let p: P = {
  name: '张三',
  age: 10
}
  • 类既可以作为类型使用,也可以作为值使用
class Person {
  name: string;
}
let p1: Person = { name: '张三' }; // 此时类作为类型使用
console.log(p1); // { name: '张三' }

let p2: typeof Person = Person; // 此时类作为值使用。Person指的是构造函数本身
console.log(p2); // [Function: Person]
  • 接口只能作为类型使用
  • 更多参考下表:
关键字作为类型使用作为值使用
classyesyes
enumyesyes
interfaceyesno
typeyesno
function ,var,let,constnoyes

3.1 合并类型声明

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

剑九_六千里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值