Method Of 类型不能用于调用方法

MethodOf type cannot be used to call the method

我想动态生成一些测试,为此我必须使用要调用的方法名称调用一个方法,然后完成所有测试设置并调用该方法。

所以基本上我调用 createTest('methodName') 而不是 it('methodName', () => ...lotsOfBoringStuff...)

为此,我想适当地输入方法,所以我有自动完成功能,并且可以肯定的是,我只为正确的方法调用它。

我设法将一些“应该工作”的东西组合在一起,但 TS 确实抱怨不兼容的类型:

type MethodOf<T> = {
  [P in keyof T]: T[P] extends () => unknown ? P : never;
}[keyof T];

function doStuff<T, N extends MethodOf<T>>(t: T, method: N): unknown {
  const meth: () => unknown = t[method]; // <-- boom: {} cannot be assigned to () => unknown
  return meth();
}

const t = {
  abc: 'str',
  foobar: () => 1,
};

doStuff(t, 'foobar');  // <-- works as expected + autocompletion

type T1 = typeof t;
type N1 = MethodOf<T1>; // 'foobar'
type M1 = T1[N1]; // () => number // <-- works as expected

为什么 TS 没有检测到 T[MethodOf<T>] 实际上是一个可调用方法? 在分配它之前是否可以将其转换为 any

我正在使用打字稿 4.6。

如果我们这样定义一个类型OnlyMethods

type OnlyMethods<T> = Pick<T, MethodOf<T>>;

然后把doStuff的签名改成这样:

function doStuff<T extends OnlyMethods<T>, N extends MethodOf<T>>(t: T, method: N): unknown {

函数体现在可以工作了:

function doStuff<T extends OnlyMethods<T>, N extends MethodOf<T>>(t: T, method: N): unknown {
  const meth = t[method]; // not even a type annotation is needed!
  return meth();          // it just WORKS
}

我相信这个 counter-intuitive 解决方案有效,因为 T 现在只是方法,而 N 只是与方法对应的键,这意味着 T[N] 总是一个方法。

Playground