私は次のようなジェネリック関数型を持っています:
type Test<TArg> = (arg: TArg) => void;
ほとんどの場合、引数は次のタイプに準拠する関数によって使用されます。
let x1: Test<number> = (n) => { console.log(n) };
let x2: Test<string> = (s) => { alert(s) };
ただし、引数をとらない関数がある場合もあります。
let y1: Test<undefined> = () => { };
次のように、呼び出しサイトで引数を指定せずにこの関数を呼び出せるようにしたいと思います。
y1();
しかし、どのタイプのプラグインを使用してもTArg
、それはできないようです。の定義でパラメータをオプションにすることなくこれを行う方法はありますTest
か?
これが私が試したことです:
type Test<TArg> = (arg: TArg) => void;
let x: Test<number> = (n) => { console.log(n) };
let y1: Test<never> = () => { };
let y2: Test<any> = () => { };
let y3: Test<undefined> = () => { };
let y4: Test<null> = () => { };
x(1);
y1(); //Expected 1 arguments, but got 0.
y2(); //Expected 1 arguments, but got 0.
y3(); //Expected 1 arguments, but got 0.
y4(); //Expected 1 arguments, but got 0.
実行ラッパーが許容できる場合は、関数の長さ(0または1)のいずれかを処理し、引数に対して型安全性のあるソリューションを考え出しました。
type Test<T> = (arg?: T) => void;
class Wrapper<T, F extends Test<T>> {
public execute: F;
public static create<T1, F1 extends Test<T1>>(method: F1): Wrapper<T1, F1> {
return new Wrapper(method);
}
constructor(method: F) {
this.execute = method;
}
}
const func1 = Wrapper.create((a: string) => console.log(a));
const func2 = Wrapper.create(() => { });
func1.execute('3');
func2.execute();
func1.execute(5); // 5 is not assignable to type "string"
func1.execute(); // expected 1 argument
func2.execute(5); // expected 0 arguments
これを1つのパラメーターを超えて拡張したい場合は、ジェネリック型を追加できますが、それぞれを手動で定義してラッパークラスを介して実行する必要がありますが、機能します。
EDITは元のオプションのパラメータソリューションを削除しました
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加