V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
xiaoming1992

函数根据入参不同,有不同的返回类型,应该怎么写函数重载?

  •  
  •   xiaoming1992 · Apr 8, 2020 · 1750 views
    This topic created in 2215 days ago, the information mentioned may be changed or developed.

    这样写是可以的, ts 不报错:

    interface GetNumber {
      name: "GetNumber";
    }
    
    interface GetString {
      name: "GetString";
    }
    
    function get(options: GetNumber): number
    function get(options: GetString): string
    function get(options: GetNumber | GetString) {
      switch (options.name) {
        case "GetNumber":
          return 1 + 1
        case "GetString":
          return `${1 + 1}`
        default:
          throw new Error("param error")
      }
    }
    
    

    下面这样不行, ts 报错: Type 'string | number' is not assignable to type 'number'.

    // 可是我的 FuncGet 类型 是从另一个文件里引入的
    // 做不到像上面那么写
    // 那么我该怎么写呢?
    interface FuncGet {
      (options: GetNumber): number;
      (options: GetString): string;
    }
    
    // ts 编译错误: Type 'string | number' is not assignable to type 'number
    const get: FuncGet = (options: GetNumber | GetString) => {
      switch (options.name) {
        case "GetNumber":
          return 1 + 1
        case "GetString":
          return `${1 + 1}`
        default:
          throw new Error("param error")
      }
    }
    
    
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2445 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 08:23 · PVG 16:23 · LAX 01:23 · JFK 04:23
    ♥ Do have faith in what you're doing.