2

TypeScript 类型技巧 - 子类方法、属性类型完善

 2 years ago
source link: https://www.fly63.com/article/detial/11312
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
更新日期: 2022-04-02阅读量: 43标签: 类型分享

扫一扫分享

出于不同的原因,我们可能希望让子类的方法、属性类型更精确。比如:

this

考虑下面的例子:

import {EventEmitter} from 'events';

class Host extends EventEmitter {
  emit(eventName: 'connect'): boolean;
  emit(eventName: 'disconnect'): boolean;
  emit(eventName: string): boolean {
    return super.emit(eventName);
  }

  on(eventName: 'connect', listener: () => void): this;
  on(eventName: 'disconnect', listener: () => void): this;
  on(eventName: string, listener: () => void): this {
    return super.on(eventName, listener);
  }
}

为了覆盖原有类型,最直接的办法就是覆盖原有方法、属性。但属性还好,覆盖原有方法必须在新的方法实现中调用父类方法,毫无营养。

此时我们可以利用 TypeScript 中的声明合并的机制处理,在这个问题下也就是通过合并 class 和 interface 声明实现类型完善:

interface Host {
  emit(eventName: 'connect'): boolean;
  emit(eventName: 'disconnect'): boolean;

  on(eventName: 'connect', listener: () => void): this;
  on(eventName: 'disconnect', listener: () => void): this;
}

class Host extends EventEmitter {}
  • 在进行声明合并时,目前 TypeScript 好像并不会进行与其父类类型兼容性的检查。
  • 当类声明中有泛型时,对应的 interface 也需要添加同名泛型。不过泛型约束( extends )和泛型默认类型( = )不需要重复添加。

祝大家举一反三。

原文 https://zhuanlan.zhihu.com/p/491506704

链接: https://www.fly63.com/article/detial/11312


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK