[英]Typescript types: check for correct callback type depending on other argument
I have a JS function我有一个 JS function
const fn = (cb, param) => {
cb(param);
};
Which is intended to be called 2 ways (in TS):打算以两种方式调用(在 TS 中):
const cb0 = () => {};
fn(cb0);
const cb1 = (param: string) => { };
fn(cb1, 'str')
fn
expectations are correctly described by this type:这种类型正确地描述了
fn
期望:
interface IFn {
(cb: (param: string) => void, param: string): void;
(cb: () => void): void;
}
fnI(cb0); // ok
// fnI(cb1); // correctly does not compile, callback needs an argument
fnI(cb1, 's'); // ok
So it checks types at caller sites.因此它会检查调用方站点的类型。 However, I can't convert
fn
to Typescript so it would not require a type cast.但是,我无法将
fn
转换为 Typescript 所以它不需要类型转换。 Moreover, it seems TS refuses to infer argument types since IFn
declares overloads.此外,似乎 TS 拒绝推断参数类型,因为
IFn
声明了重载。 The best I can do is:我能做的最好的事情是:
const fn: IFn = <IFn>((cb: (param?: string) => void, param?: string) => {
cb(param);
});
The problem is the implementation signature is less restrictive and the following implementation clearly violates assertions of IFn
but the violation can't be detected by type checker.问题是实现签名的限制较少,并且以下实现明显违反了
IFn
的断言,但类型检查器无法检测到违规。
const fn: IFn = <IFn>((cb: (param?: string) => void, param?: string) => {
cb(param === undefined ? 'some other string' : undefined);
});
So the question is: Is it possible to define fn
signature or IFn
so the above assertions violation inside of the implementation would be found by TypeScript?所以问题是:是否可以定义
fn
签名或IFn
,以便 TypeScript 发现实现内部的上述断言违规?
Obviously, I'm not interested in runtime checks.显然,我对运行时检查不感兴趣。
Try this:尝试这个:
interface IFn {
(cb: (param: string) => void, param: string): void;
(cb: () => void): void;
}
const fn: IFn = (
...args: [(param: string) => void, string] | [() => void]
) => {
switch (args.length) {
case 2: {
const cb = args[0];
const param = args[1];
cb(param);
break;
}
case 1: {
const cb = args[0];
cb();
break;
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.