2016-10-10 58 views
0

我想了解这是否可能?打字稿接口实现迭代器<T>

export interface ISomething { ... } 
export interface ISomethingElse implements Iterator<ISomething> { ... doSomeJob(): void; ... } 

的想法是,当我宣布我的课,我的ClassA可以做这样的事情......

export ClassA implements ISomethingElse { 

public doSomeJob(): void { 
    for (let item of this) { 
     console.log(item); 
    } 
} 

} 

我期待实现的东西,行为像这样的声明在C#

public interface ISomethingElse : IEnumerable<ISomething> { 
    void DoSomeJob(); 
} 
+0

不应该是'export interface ISomethingElse extends Iterator '而不是'export interface ISomethingElse implements Iterator '? AFAIK,这是继承接口的方式 –

+0

我想你会想实现'Iteratable'而不是'Iterator' ... –

回答

1

如果你想使用Iterator,那么你可以这样做:

interface ISomething { } 

interface ISomethingElse extends Iterator<ISomething> { 
    doSomeJob(): void; 
} 

class ClassA implements ISomethingElse { 
    private counter: number = 0; 

    public next(): IteratorResult<ISomething>{ 
     if (++this.counter < 10) { 
      return { 
       done: false, 
       value: this.counter 
      } 
     } else { 
      return { 
       done: true, 
       value: this.counter 
      } 
     } 

    } 

    public doSomeJob(): void { 
     let current = this.next(); 
     while (!current.done) { 
      console.log(current.value); 
      current = this.next(); 
     } 
    } 
} 

code in playground

但是,如果你想使用for/of循环,那么你就需要使用Iterable

interface ISomethingElse extends Iterable<ISomething> { 
    doSomeJob(): void; 
} 

class ClassA implements ISomethingElse { 
    [Symbol.iterator]() { 
     let counter = 0; 

     return { 
      next(): IteratorResult<ISomething> { 
       if (++this.counter < 10) { 
        return { 
         done: false, 
         value: counter 
        } 
       } else { 
        return { 
         done: true, 
         value: counter 
        } 
       } 
      } 
     } 
    } 

    public doSomeJob(): void { 
     for (let item of this) { 
      console.log(item); 
     } 
    } 
} 

code in playground

但是,你需要为目标es6,否则你会得到在for/of回路的误差(如在操场):

类型“这”不是数组类型或者一个字符串类型

你可以找到关于这个位置的详细信息:
Iterators and generators
这里:
Iteration protocols

+0

太好了,谢谢。我不需要具体的for循环,但因为我已经瞄准es6我没有使用Iterable 的问题。 – Daz

0

我认为您正在为interfaces寻找extends

摘录:

扩展接口

象类,接口可以彼此延伸。这允许您将一个接口的成员复制到另一个接口的成员,这使您可以更灵活地将接口分成多个可重用组件。

interface Shape { 
    color: string; 
} 

interface Square extends Shape { 
    sideLength: number; 
} 

let square = <Square>{}; 
square.color = "blue"; 
square.sideLength = 10;