2016-10-10 56 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;