简体   繁体   English

TypeScript:如何从函数类型中获取许多参数

[英]TypeScript: How to get a number of parameters from function types

Is there any good way to get a number of parameters from function types? 有什么好方法可以从函数类型中获取许多参数?

For example, I have two callback functions as function type and a setter function for them. 例如,我有两个回调函数作为函数类型和一个setter函数。 I want to get a number of parameters from function types and replace the magic numbers (2, 3) with it. 我想从函数类型中获取一些参数,并用它替换幻数(2,3)。

type Callback1 = (a: number, b: string) => void;
type Callback2 = (a: number, b: string, b: boolean) => void;

setCallback(callback: Callback1 | Callback2): void {
    if (callback.length == 2) {
        this.callback = callback as Callback1;
    } else if (callback.length == 3) {
        this.callback = callback as Callback2;
    }
}

Use the length property. 使用length属性。

let x = function (a,b){}
function bar (a,b){}
console.log(x.length, bar.length); // 2,2 

More 更多

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/length https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Function/length

This works for me. 这对我有用。 If the definition of the function types changes, compilation fails at the dummy function definitions. 如果函数类型的定义发生更改,则伪函数定义的编译将失败。 This is much safer than the magic numbers above. 这比上面的魔术数字安全得多。

type Callback1 = (a: number, b: string) => void;
type Callback2 = (a: number, b: string, b: boolean) => void;

private readonly dummyCallback1: Callback1 = (a: number, b: string) => {};
private readonly dummyCallback2: Callback2 = (a: number, b: string, b: boolean) => {};

setCallback(callback: Callback1 | Callback2): void {
    if (callback.length == this.dummyCallback1.length) {
        this.callback = callback as Callback1;
    } else if (callback.length == this.dummyCallback2.length) {
        this.callback = callback as Callback2;
    }
}

This is much simpler. 这要简单得多。 Thanks @torazaburo 谢谢@torazaburo

type Callback = (a: number, b: string, c?: boolean) => void;

setCallback(callback: Callback): void {
    this.callback = callback as Callback1;
}


setCallback(0, "a");
setCallback(0, "a", true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM