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つの割り当てのエラーを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")