【问题标题】:Require parameter of given type based on another parameter in TypeScript需要基于 TypeScript 中的另一个参数的给定类型的参数
【发布时间】:2020-05-31 01:19:34
【问题描述】:

让我们拥有发送电子邮件的 TypeScript 功能:

enum ETemplate {
  EXAMPLE1, EXAMPLE2
}

function sendEmail(to: string, template: ETemplate, params: IParams): Promise<void>{
  await this.mailService.send(to, template, params);
}

interface IParams {
  // depends on template type (ETemplate)
}

如何根据我输入的模板类型要求params?原因是因为每个模板在ETemplate 的基础上都有不同的IParams

我知道 TypeScript 有泛型,但我不确定我是否可以用它们实现这一点...

【问题讨论】:

    标签: typescript generics interface typescript-typings


    【解决方案1】:

    在这种情况下,您不需要使用泛型。请改用discriminated unions

    enum TemplateType {
        Template1,
        Template2
    }
    
    type Template =
        | { type: TemplateType.Template1, params: { aaa: number } }
        | { type: TemplateType.Template2, params: { bbb: string, ccc?: boolean } };
    
    const sendEmail = async (to: string, template: Template): Promise<void> => {
        if (template.type === TemplateType.Template1) {
            template.params.aaa; // number
    
            return;
        }
    
        if (template.type === TemplateType.Template2) {
            template.params.bbb; // string
            template.params.ccc; // boolean | undefined
    
            return;
        }
    
        template; // never
    }
    
    
    sendEmail("example@example.com", { type: TemplateType.Template1, params: { aaa: 123 } }); // OK
    sendEmail("example@example.com", { type: TemplateType.Template2, params: { aaa: 123 } }); // Error as expected
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 2017-05-12
      • 2023-02-22
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多