在子类或接口上定义的 Typescript 专用重载 [英] Typescript specialized overloads defined on a subclass or interface

查看:23
本文介绍了在子类或接口上定义的 Typescript 专用重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使下面的工作不必在子类中定义一个简单地调用超类或不必要地重复非专用签名的实现?

Is there a way to make the following work without having to define an implementation in the subclass which simply calls the superclass or unnecessarily repeats the non-specialized signature?

class Emitter {
    on(name: 'one', handler: (value: number) => void): void;
    on(name: string, handler: (...args: any[]) => void): void;
    on(name: string, handler: (...args: any[]) => void): void { 
        // do stuff
    }
}


class Subclass extends Emitter {
    on(name: 'two', handler: (value: string) => void): void;
    on(name: string, handler: (...args: any[]) => void): void;
    // error no implementation specified
}


interface IEmitter {
    on(name: 'one', handler: (value: number) => void): void;
    on(name: string, handler: (...args: any[]) => void): void;
}


interface ISubclass extends IEmitter {
    on(name: 'two', handler: (value: string) => void): void;
    // error overload not assignable to non specialized
}

推荐答案

函数重载只有在它们是对象类型的调用签名时才会被合并.最简单的解决方法(对于接口案例)是将函数类型分离成它自己的接口并扩展它:

Function overloads only get combined if they are call signatures on an object type. The easiest fix (for the interface case) is to separate out the function type into its own interface and extend that:

interface EmitterEvent {
    (name: 'one', handler: (value: number) => void): void;
    (name: string, handler: (...args: any[]) => void): void;
}

interface SubclassEmitterEvent extends EmitterEvent {
    (name: 'two', handler: (value: string) => void): void;
}

interface IEmitter {
    on: EmitterEvent;
}

interface ISubclass extends IEmitter {
    on: SubclassEmitterEvent;
}

var x: ISubclass;
x.on('one', n => n.toFixed()); // n: number
x.on('two', s => s.substr(0)); // s: string
var y: IEmitter;
y.on('two', a => a); // a: any

类案例中的等效版本需要一些工作(假设您关心原型上的函数——如果不是,只需使用函数表达式作为 on 的初始化器):

The equivalent version in the class case takes some work (assuming you care about the function going on the prototype -- if not, just use a function expression as an initializer for on instead):

class Emitter {
    on: EmitterEvent;
}
module Emitter {
    Emitter.prototype.on = function(name: string, handler: any) {
        // Code here
    }
}

这篇关于在子类或接口上定义的 Typescript 专用重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆