【问题标题】:How to refactor function overloads with different arity without using overloads?如何在不使用重载的情况下重构具有不同数量的函数重载?
【发布时间】:2019-12-22 06:08:22
【问题描述】:

我有一个不同数量的打字稿函数声明:

function f(): void;
function f(code: 0): void;
function f(code: 1, msg: string): void;
function f(code: 0 | 1 = 0, msg?: string): void { /* omit implementation */ }

因此它可以被调用为:

f() // ok
f(0) // ok
f(1, "error message") // ok
f(0, "message") // type error
f(1) // type error

我的问题是如何在不使用函数重载的情况下重构这个函数声明? (例如,联合类型、条件类型等)

【问题讨论】:

    标签: typescript overloading typescript-typings


    【解决方案1】:

    以下是您可以使用联合类型键入参数组合的方法:

    function f(...args: [] | [0] | [1, string]): void { /* omit implementation */ }
    

    Playground

    * 带有重载的版本看起来仍然干净得多。

    【讨论】:

      【解决方案2】:

      这个呢?

      type Message = {code: 0 } | {code: 1, messageText?: string};
      
      const useMessage = (message?: Message) => {};
      
      const usedMessage_0 = useMessage();
      const usedMessage_1 = useMessage({code: 0});
      const usedMessage_2 = useMessage({code: 1});
      
      const usedMessage_3 = useMessage({code: 0, messageText: 'something'}); // type error
      const usedMessage_4 = useMessage({code: 1, messageText: 'something'});
      
      

      【讨论】:

        猜你喜欢
        • 2014-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        相关资源
        最近更新 更多