代码之家  ›  专栏  ›  技术社区  ›  ThirstyMonkey

当重载字符串参数时,为什么在实现之前必须有一个通用类型声明?

  •  0
  • ThirstyMonkey  · 技术社区  · 7 年前

    any 在使用某些参数调用时可以正确键入。

    这在规范中有两处定义: https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#1.8 https://github.com/Microsoft/TypeScript/blob/master/doc/spec.md#3.9.2.4

    get 。我想提供传递字符串时的特定类型 "a" "b" 任何 .

    x y ,但如果我删除一般签名( get(name: string): any ),我得到错误: Argument of type '"c"' is not assignable to parameter of type '"b"'.

    export default class Example {
      contents: any
      get(name: "a"): number
      get(name: "b"): string
      // Why is this required???
      get(name: string): any
      get(name: string): any { return this.contents[name] }
    }
    
    
    let w = new Example()
    
    // Expected errors
    // Type 'number' is not assignable to type 'string'.
    let x: string = w.get("a")
    // Type 'string' is not assignable to type 'number'.
    let y: number = w.get("b")
    
    // I get an error here only if I remove the general signature before the
    // implementation of get.
    // Argument of type '"c"' is not assignable to parameter of type '"b"'.
    let z: string[] = w.get("c")
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Adrian Leonhard    7 年前

    section 6.2 of the spec, "Function overloads"

    注意,类型中不包括实际函数实现的签名。

    这是有意义的,因为实现的签名需要匹配所有可能的签名,如果它包含在最终签名中,这可能会导致比我们实际想要的更一般的签名。例如:

    function foo(type: "number", arg: number)
    function foo(type: "string", arg: string)
    function foo(type: "number" | "string", arg: number | string) {
        // impl here
    }
    

    foo("number", "string param")