简体   繁体   English

基于泛型的条件方法参数

[英]Conditional method parameters based on Generic type

I am in the process of writing a new TypeScript class which takes a generic value that will be used as the input to a function. 我正在编写一个新的TypeScript类,该类具有一个将用作函数输入的通用值。 If a value isn't given, than the function should not take any inputs. 如果未提供值,则该函数不应接受任何输入。

Ideally the class would be overloaded like this. 理想情况下,此类将像这样重载。

class Emitter<T = void> {
    public activate(): void // When T is void
    public activate(arg: T): void // When T isn't void
    public activate(arg?: T) { /* ... */ }
}

Having the method be a function property works in theory but requires a @ts-ignore on the method's implementation. 使该方法成为函数属性在理论上是@ts-ignore但是需要对该方法的实现使用@ts-ignore

type OneArgFn<T> = T extends void
    ? () => void
    : (arg: T) => void

interface Emitter<T> {
    readonly activate: OneArgFn<T>
}

Another possibility is to export a different constructor when a Generic is provided or not, such as the following 另一种可能性是在是否提供泛型时导出不同的构造函数,例如以下内容

interface EmitterNoArg extends Emitter {
    activate: () => true
}
interface EmitterOneArg<T> extends Emitter<T> {
    activate: (arg: T) => void
}

interface EmitterConstructor {
    new(): Emitter

    new(): EmitterNoArg
    new<T>(): EmitterOneArg<T>
}

but then to export it the unknown keyword is required. 但要导出该关键字,则需要unknown关键字。

export default Emitter as unknown as EmitterConstructor

These, do not seem to be optimal. 这些似乎不是最佳的。 Is there a proper way to have conditional arguments based on the Generic's type? 是否有适当的方法可以基于泛型的类型获取条件参数? I would think TypeScript's new conditional types would solve this issue. 我认为TypeScript的新条件类型将解决此问题。

One way to do it would be using tuples in rest parameters in a separate public signature: 一种方法是在单独的公共签名中的rest参数中使用元组:

type OneArgFn<T> = T extends void
    ? () => void
    : (arg: T) => void

class Emitter<T = void> {
    public activate(...a: Parameters<OneArgFn<T>>): void
    public activate(arg?: T) { /* ... */ }
}

new Emitter().activate();
new Emitter<string>().activate("") // in 3.4 argument names are preserved

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM