受限回调参数

问题描述 投票:0回答:1

我有这个:

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);

目前大多数这些也不起作用...... 我该如何解决这个问题?

游乐场

typescript
1个回答
0
投票

回调参数被 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);
© www.soinside.com 2019 - 2024. All rights reserved.