English 中文(简体)
字典中通用固定构造
原标题:Generic static constructor in TypeScript
  • 时间:2023-12-27 16:47:14
  •  标签:
  • typescript

我倾向于使用静态构造器Foo.of(/Foo. from(<>/code>)方法,而不是必须用new的典型类别构造。 我认为,这三者更容易阅读,同样,可以免费使用。 然而,我最后写了很多象这样的碎块:

class Foo<T> {
  constructor(private value: T) {}
  static of<T>(value: T) {
    return new Foo(value);
  }
}

class Bar<T, U> {
  constructor(private value1: T, private value2: U) {}
  static of<T, U>(value1: T, value2: U) {
    return new Bar(value1, value2);
  }
}

是否有任何办法,例如使用一台装饰器(+一个接口,可能),以避免不得不宣布。 每次都采用这种方法,但可以采取类似做法:

type Constructor = new (...args: any) => any;
interface Constructable<T extends Constructor> {
  static of(...args: Parameters<T>): T;
}

function constructable<T>(constructor: Constructor) { ... }

// ....

@constructable
class Foo<T> {
    constructor(private value: T) {}
}
interface Foo<T> extends Constructable<Foo<T>> {}

@constructable
class Bar<T, U> {
    constructor(private value1: T, value2: U) {}
}
interface Bar<T, U> extends Constructable<Bar<T, U>> {}

const foo = Foo.of(10)
const bar = Bar.of(10, 20)
问题回答

你可以使用助手功能,而不是装饰器。

故意设计出“用于计量和增加价值的功能”, 无<>/m>从根本上改变其对外行为”(tc39/proposal-decorators: ES6年级考试:, α>/m>。 将新的静态方法添加到建筑类将从根本上改变其对外行为,因为它改变了其公共接口。

如果你出口和进口助手功能,那么你会发现,写小块碎块更容易,但这里可以举出你可以做些什么的例子:

function of<T, P extends unknown[]>(constructor: new (...args: P) => T) {
  return (...args: P) => new constructor(...args);
}

class Foo<T> {
  constructor(private value: T) {}
  static of = of(this);
}

class Bar<T, U> {
  constructor(private value1: T, private value2: U) {}
  static of = of(this);
}

const foo = Foo.of(10);
//    ^? const foo: Foo<number>
const bar = Bar.of(10, 20);
//    ^? const bar: Bar<number, number>

型号将不再作为methods处理<<>Foo.of()和Bar.of(>>。 但是,作为properties,其中有一些细微的下层(见 功能财产与方法)。





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签