我有这个:
const any = (any?: any): any => any;
export type Fn = (cb: (...args: (string | number)[]) => any) => any;
const Fn: Fn = any();
const t1 = Fn((x: unknown) => x); // Allowed
const t2 = Fn(<X>(x: X) => x); // Allowed
如何禁止回调中使用未知参数?
我已经尝试过:
strictFunctionTypes
于 tsconfig.json
Exact
实用程序类型cb
声明中使用泛型到目前为止,这些都对我不起作用。 那么,如何在没有约束参数的情况下避免回调。
以下是应该允许的:
const t3 = Fn((a: string, b: number) => {});
const t4 = Fn(() => {});
const t5 = Fn((x: string | number, y: string) => {});
const t6 = Fn(<X extends number>(x: X) => x);
const t7 = Fn(<X extends string, Y extends string>(x: X, y: Y) => x + y);
目前大多数这些也不起作用...... 我该如何解决这个问题?
回调参数被 TS 特殊对待。因此,在您的情况下,每个参数都应该是
string|number
。如果您将 args 设为通用,那么它有望按您的预期工作:
const any = (any?: any): any => any;
export type Fn = (cb: (...args: (string | number)[]) => any) => any;
const Fn = <T extends (string | number)[]>(cb: (...args: T) => any) => cb;
const t1 = Fn((x: unknown) => x); // Allowed
const t2 = Fn(<X, >(x: X) => x); // Allowed
const t3 = Fn((a: string, b: number) => {});
const t4 = Fn(() => {});
const t5 = Fn((x: string | number, y: string) => {});
const t6 = Fn(<X extends number>(x: X) => x);
const t7 = Fn(<X extends string, Y extends string>(x: X, y: Y) => x + y);