我一直试图为一个外部的JavaScript包编写类型,该包提供一个大对象,其属性(主要)是一堆不同的类构造函数.一些类似的事情

class ThingOne {
  constructor(par1, par2) { // guts expecting par1 to be a ThingTwo and par2 a number... }
  aMethod(par) { // wants a string... } 
  // etc etc
}

class ThingTwo {
  constructor(par1, par2) { // wants a string and a boolean... }
  // etc etc
}

var bigObject = { \\ this is what comes out of the package
   ThingOne: ThingOne,
   ThingTwo: ThingTwo
}

(在现有套餐中),其预期用途为

const myTwo = new bigObject.ThingTwo('foo', true);
const myOne = new bigObject.ThingOne(myTwo, 7); 
// etc.

因此,在.d.ts文件中,我正在手工编写代码,并try 编写一个接口,用来输入bigObject.我的第一次try 是

export interface BigObjectInterface {
  ThingOne(par1: ThingTwo, par2: number): ThingOne;
  ThingTwo(par1: string, par2: boolean): ThingTwo
}

export class ThingOne {
  constructor(par1: ThingTwo, par2: number);
  aMethod(par: string); // etc.
}

export class ThingTwo {
  constructor(par1: string, par2: boolean);
  // etc.
}

但正如我所期望的那样,这不起作用,因为它为用法键入

const myTwo = bigObject.ThingTwo('foo', true);

与预期的new操作员不同.另一方面,接口中的new不带方法名,所以我不知道如何使用它.我也不能将BigObjectInterface中的ThingOne属性仅键入为ThingOne(例如ThingOne: ThingOne),因为它不是ThingOne对象,它只是ThingOne的构造函数的别名(例如bigObject.ThingOne.aMethod('bar')不合法).

那么,如何才能将BigObjectInterface中的ThingOneThingTwo属性分类呢?

推荐答案

对声明的最小更改是使用the typeof operator来获取ThingOne/ThingTwo构造函数values的类型,这样您就可以直接使用这些类型,而不是try 为它们重写类型:

interface BigObjectInterface {
  ThingOne: typeof ThingOne;
  ThingTwo: typeof ThingTwo;
}

const myTwo = new bigObject.ThingTwo('foo', true); // okay
const myOne = new bigObject.ThingOne(myTwo, 1); // okay

另一方面,如果您确实想写出类型,则可以将ThingOneThingTwo属性设置为construct signatures:

interface BigObjectInterface {
  ThingOne: { new(par1: ThingTwo, par2: number): ThingOne };
  ThingTwo: { new(par1: string, par2: boolean): ThingTwo }
}

const myTwo = new bigObject.ThingTwo('foo', true); // okay
const myOne = new bigObject.ThingOne(myTwo, 1); // okay

Playground link to code

Typescript相关问答推荐

Typescript自定义键映射

如何根据参数的值缩小函数内的返回类型?

动态调用类型化函数

将对象属性转换为InstanceType或原样的强类型方法

类型脚本类型字段组合

当方法参数和返回类型不相互扩展时如何从类型脚本中的子类推断类型

Angular 17子路由

Fp-ts使用任务的最佳方法包装选项

创建依赖函数参数的类型

如何使这种一对一关系在旧表上起作用?

是否将Angular *ngFor和*ngIf迁移到新的v17语法?

任何导航器都未处理有效负载为";params";:{";roomId";:";...";}}的导航操作

TS不能自己推断函数返回类型

如何在Vue动态类的上下文中解释错误TS2345?

如何在TypeScript类成员函数中使用筛选后的keyof this?

有没有一种简单的方法可以访问Keyboard Shortcuts JSON文件中列出的每个命令的显示名称(标题)?

数据库中的表请求返回如下日期:2023-07-20T21:39:00.000Z 我需要将此数据格式化为 dd/MM/yyyy HH:mm

对于通过 Axios 获取的数据数组,属性map在类型never上不存在

Select 器数组到映射器的Typescript 泛型

const 使用条件类型时,通用类型参数不会推断为 const