2017-08-02 3 views
0

TypeScriptは文字列パラメータのオーバーロードをサポートしているため、特定の引数を指定して呼び出すと、anyを返すメソッドを正しく型指定できます。これは、2つの場所での仕様で定義されている文字列パラメータのオーバーロード時に実装前に一般的な型宣言が必要なのはなぜですか?

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"をこの関数に渡すときの特定の型を指定したい場合は、戻り値の型がanyになるようにします。

私は2つの特殊なシグネチャを含み、一般的なシグネチャを提供し、一般的なシグネチャを持つ実装を提供します。次のコードは、最初の2つの割り当てのエラーをxyに正しく報告しますが、一般的な署名(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") 

答えて

2

section 6.2 of the spec, "Function overloads"

Note that the signature of the actual function implementation is not included in the type.

の最後の行は、これは、理にかなって、それが最終的に署名に含まれている場合、これはつながります私たちが実際に望むよりも一般的な署名に変換します。たとえば:

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") 
関連する問題