构造函数中的TypeScript收缩参数类型



我有一个名为BackgroundLayer的入口类。它需要两个参数,(1(背景的类型和(2(背景的配置。当(1(的类型为Background.Grid时,则配置的类型需要为GridBackgroundConfig。当(1(是Background.Checkered类型时,配置需要是CheckeredBackgroundConfig类型。我想要的是,当键入new BackgroundLayer(Background.Grid时,配置(参数2(需要是GridBackgroundConfig的类型。下面的源代码是我的尝试,但它允许将Background.Grid传递为(1(,将CheckeredBackgroundConfig类型的对象传递为(2(,这是不允许的。我尝试使用多个构造函数实现(constructor(type: Background.Grid, config: GridBackgroundConfig); constructor(type: BackgroundEnum.Checkered,config: CheckeredBackgroundConfig);,但随后我需要手动为Background中的每个条目创建一个新的构造函数

enum Background {
Grid = "Grid";
Checkered = "Checkered";
}
interface LayerConfig {
/* ... */
}
interface GridBackgroundConfig extends LayerConfig {
/* ... */
}
interface CheckeredBackgroundConfig extends LayerConfig {
/* ... */
}
class Layer {
protected config: LayerConfig;
constructor(config: LayerConfig) {
this.config = config;
}
}
class BackgroundLayer extends Layer {
private background: Background;
constructor(type: Background, config: GridBackgroundConfig | CheckeredBackgroundConfig) {
super(config);
if (type === Background.Grid) {
this.background = new Grid(config as GridbackgroundConfig);
} else if (type === Background.Checkered) {
this.background = new Checkered(config as CheckeredBackgroundConfig);
} else {
throw "check argument types";
}
}
}
class Grid {
private config: GridBackgroundConfig;
constructor(config: GridBackgroundConfig) {
this.config = config;
}
}
class Checkered {
private config: CheckeredBackgroundConfig;
constructor(config: CheckeredBackgroundConfig) {
this.config = config;
}
}

您可能应该坚持在这里使用重载,但无论如何,如果您定义了一个将背景类型映射到各自配置的类型。。。

type ConfigMap = {
[Background.Grid]: GridBackgroundConfig;
[Background.Checkered]: CheckeredBackgroundConfig;
};

您应该能够使您的类通用,并编辑构造函数以使用类型参数:

class BackgroundLayer<Type extends Background> extends Layer {
private background: Grid | Checkered;
constructor(type: Type, config: ConfigMap[Type]) {

那么CCD_ 7的类型取决于给予CCD_。

游乐场

相关内容

最新更新