gpt4 book ai didi

javascript - 导出类的变体

转载 作者:搜寻专家 更新时间:2023-10-30 20:59:35 28 4
gpt4 key购买 nike

我正在尝试导出我想导入到其他地方的类的一些变体。我不知道是否可以在不实例化的情况下创建它们?以及我该怎么做。

这是我现在拥有的

index.ts

export { Character } from './Character';

Character.ts

import { CharacterOptions, WarlockOptions } from './CharacterOptions';

class Character implements CharacterInterface {
private health: number;
private name: string;
private characterOptions: CharacterOptions;

constructor(name, health) {
this.name = name;
this.health = health;
this.characterOptions = new WarlockOptions(); // where WarlockOptions extends CharacterOptions
}
}

我希望能够在 index.ts 文件中做类似的事情

import { Character } from './Character';
import { ArcherOptions, WarlockOptions } from './CharacterOptions';

export const ArcherClass = someWrapperOfCharacter(ArcherOptions);
export const WarlockClass = someWrapperOfCharacter(WarlockOptions);

比如动态创建(通过 someWrapperOfCharacter())我可以公开的新的特定类。

我知道我可以直接创建扩展 Character 的类,但我尽量避免这样做,因为:

  • 我不知道将来会有多少个CharacterOptions
  • 每次我想添加一个新的 CharacterOptions
  • 时,我都不想被迫创建一个新的变体
  • 我想允许通过传递扩展 CharacterOptions
  • 的自定义对象来直接创建自定义类

最佳答案

您可以将选项的构造函数传递给类,并有一个函数创建派生类型,将选项类设置为特定实现:

interface CharacterInterface { }

class CharacterOptions { public level?: number }
class ArcherOptions extends CharacterOptions { public bow?: string; }
class WarlockOptions extends CharacterOptions { public magic?: string }


class Character<T extends CharacterOptions> implements CharacterInterface {
private health: number;
private name: string;
private characterOptions: T;

constructor(name: string, health: number, optionsCtor: new () => T) {
this.name = name;
this.health = health;
this.characterOptions = new optionsCtor(); // where WarlockOptions extends CharacterOptions
}
}
function someWrapperOfCharacter<T extends CharacterOptions>(optionsCtor: new () => T) {
return class extends Character<T> {
constructor(name: string, health: number) {
super(name, health, optionsCtor);
}
}
}

export const ArcherClass = someWrapperOfCharacter(ArcherOptions);
export type ArcherClass = InstanceType<typeof ArcherClass> // needed to allow type declarations let a: ArcherClass

export const WarlockClass = someWrapperOfCharacter(WarlockOptions);
export type WarlockClass = InstanceType<typeof WarlockClass>

关于javascript - 导出类的变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55783396/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com