と呼ばれる私はtypescriptですがタイピングは機能のオブジェクトがあるパターンとによってオブジェクトに機能を見上げ機能call(name, arg)
で動作するようにしようとしていますname
とし、それをarg
と呼びます。型推論マップから解決し、間接的に
は、私は関数に名前をマップするオブジェクトがあるとします。
interface Registry {
str2numb: (p: string) => number
num2bool: (p: number) => boolean
}
const REGISTRY: Registry = {
str2numb: p => parseInt(p, 10),
num2bool: p => !!p,
}
私もREGISTRY
から機能を解決し、p
でそれを呼び出す関数call(name, p)
を持っています。私はタイプからパラメータp
用タイプP
(とも戻り値の型R
)を解決するにはどうすればよい
const call = (name, p) => REGISTRY[name](p)
call('str2numb', 123)
// ^^^ Would like to see an error here
:今、私は、無効な引数が提供されている場合、それは文句ことなので、機能を入力したいですRegistry.str2numb
?それも可能ですか?
// How can I resolve P and R here?
// The resolved function is Registry[N]
// I have tried Registry[N]<P, R> but that doesn't work :-(
const call = <N extends keyof Registry>(name: N, p: P): R => REGISTRY[name](p)
私はここまで得ているが、それは動作しません。しかしこれは動作します
type Fn<P, R> = (p: P) => R
const call =
<N extends keyof Funcs, F extends Funcs[N] & Fn<P, R>, P, R>
(name: N, p: P): R =>
REGISTRY[name](p)
call('str2numb', 123)
// ^^^ No error here
:
// This just returns the resolved function
const call1 = <N extends keyof Funcs>(name: N) => REGISTRY[name]
// The type of the returned function is correctly inferred from the name
call1('str2numb')(123)
// ^^^ Argument of type '123' is not assignable to parameter of type 'string'