打字稿:为库类方法创建类型

时间:2020-05-20 02:55:46

标签: typescript

在很多情况下,我想基于类方法(通常从库类提供)创建 helper类型。但是我似乎不太清楚。

理想情况下,类似于以下内容将非常有用。但这似乎在这种情况下不起作用。

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

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

1 个答案:

答案 0 :(得分:0)

好的,我通过查看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

也很重要

enter image description here