首页 > 解决方案 > Typescript:为库类方法创建类型

问题描述

在很多情况下,我想基于类方法(通常由库类提供)创建辅助类型。但我似乎无法弄清楚。

理想情况下,以下内容会很棒。但在这种情况下它似乎不起作用。

// Library code
declare class LibClass {
  Method1(something: number): Promise<string>;
}
// My application code
type LibMethodType = ReturnType<LibClass.Method1>

有人对如何解决这个问题有任何建议吗?

标签: typescript

解决方案


好的,我通过查看 ts-error 找到了答案。以下是如何实现这一点:

declare class LibClass {
  Method1(something: number): string;
}

// Needs to
type LibMethodType = LibClass['Method1']

const myFunction: LibMethodType = (s: number) => s.toString()

LibClass['Method1']使用语法而不是使用语法也很重要LibClass.Method1

在此处输入图像描述


推荐阅读