首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在类型记录中根据类的类型动态实例化类数组

如何在类型记录中根据类的类型动态实例化类数组
EN

Stack Overflow用户
提问于 2020-04-10 16:21:06
回答 1查看 84关注 0票数 0

我实现了如下的策略模式

代码语言:javascript
复制
interface IRule {
  isMatch(n: number): boolean;
}

class Rule1 implements IRule {
  isMatch(n: number) {
    return n === 7;
  }
}

class Rule2 implements IRule {
  isMatch(n: number) {
    return n % 2 === 0;
  }
}

class Factory {
  readonly rules: IRule[];

  constructor() {
    this.rules = [new Rule1(), new Rule2()];
  }

  public of(n: number) {
    return this.rules.find(r => r.isMatch(n));
  }
}

const found = new Factory().of(7);

问题:

TypeScript中是否有一种基于类类型IRule动态创建Factory.Rules的方法?

在C#中,可以这样做:

代码语言:javascript
复制
var ruleTypeInterface = typeof(IRule);
var rulesType = Assembly.GetExecutingAssembly()
                        .GetTypes()
                        .Where(t => ruleTypeInterface.IsAssignableFrom(t) && t.IsClass);
this.rules = rulesType.Select(rt => Activator.CreateInstance(rt) as IRule).ToArray();
EN

回答 1

Stack Overflow用户

发布于 2021-01-24 05:55:29

你是在正确的轨道上,但有一些句法错误。

代码语言:javascript
复制
class Rule1: IRule {
  isMatch(in: number) {
    return number === 7;
  }
}

当您有一个实现classinterface时,您可以编写class Rule1 implements IRule而不是class Rule1: IRule

inisMatch方法中的变量名,number是类型,但是您使用的是number,就好像它是变量名一样。in也是一个保留字,所以让我们用n代替。

您的Factory具有相同的in保留字问题。它还存在一个错误A class member cannot have the 'const' keyword。也许你想让它成为readonly

代码语言:javascript
复制
interface IRule {
  isMatch(n: number): boolean;
}

class Rule1 implements IRule {
  isMatch(n: number) {
    return n === 7;
  }
}

class Rule2 implements IRule {
  isMatch(n: number) {
    return n % 2 === 0;
  }
}

class Factory {
  readonly rules: IRule[];

  constructor() {
    this.rules = [new Rule1(), new Rule2()];
  }

  public of(n: number) {
    return this.rules.find(r => r.isMatch(n));
  }
}

const found = new Factory().of(7);

现在一切都成功了。推断的found类型是IRule | undefined,因为我们不知道(仅基于这些类型) of是否会找到匹配。

打字稿游乐场链接

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61144379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档