如何使用Typescript从枚举输入中推断方法返回类型?

时间:2019-07-14 09:02:36

标签: typescript

我有一个AudioProcessor枚举:

export enum AudioProcessors {
  BiquadFilter = 'BiquadFilter',
  StereoPanner = 'StereoPanner',
  DynamicsCompressor = 'Dynamics​Compressor​',
  None = 'None'
}

和AudioProcessorNode类型:

export type AudioProcessorNode = BiquadFilterNode | StereoPannerNode | DynamicsCompressorNode;

我想创建一个使用枚举并从相应的类属性返回对应的Node的类方法,但是我不确定如何使Typescript推断类型,以便:

public getProcessor(audioProcessor: AudioProcessors): AudioProcessorNode {        
   throw new Error(`Method not implemented. ${audioProcessor}`);
}

audioClass.getProcessor(AudioProcessors.BiquadFilter) // returns BiquadFilterNode 

看起来我需要的是类似ReturnType的东西,但我不知道如何将其放入方法签名中。

1 个答案:

答案 0 :(得分:2)

您可以使用重载使该方法返回适当的类型:

public getProcessor(audioProcessor: AudioProcessors.BiquadFilter): BiquadFilterNode 
public getProcessor(audioProcessor: AudioProcessors.DynamicsCompressor): DynamicsCompressorNode
public getProcessor(audioProcessor: AudioProcessors.StereoPanner): StereoPannerNode 
public getProcessor(audioProcessor: AudioProcessors): AudioProcessorNode {        
    throw new Error(`Method not implemented. ${audioProcessor}`);
}

或者您可以使用从枚举成员到适当的返回类型的映射接口:

interface AudioProcessorNodeMap {
    [AudioProcessors.BiquadFilter] : BiquadFilterNode;
    [AudioProcessors.DynamicsCompressor] : DynamicsCompressorNode;
    [AudioProcessors.StereoPanner] : StereoPannerNode;
    [AudioProcessors.None] : void;
}

class x{

    public getProcessor<T extends AudioProcessors>(audioProcessor: T): AudioProcessorNodeMap[T]
    public getProcessor(audioProcessor: AudioProcessors): AudioProcessorNode {        
        throw new Error(`Method not implemented. ${audioProcessor}`);
    }
}


此版本的优点是,如果您忘记在接口中添加成员,则会在方法上出现错误。