2017-08-18 17 views
0

ぎこちないトランスペイラの動作が発生したとき、私はジェネレータを使用して列車を維持しています。もちろん、私は--strictNullChecksを使用します。TypeScript - イテレータで投げたときの定義されていないコンパイルエラー

function* generat(end: number) { 
    for (let i = 0; i <= end; i++) { 
    try { 
     yield i; 
    } catch (e) { 
     console.log(e); 
    } 
    } 
} 

let iterat = generat(5); 

console.log(iterat.next()); 
console.log(iterat.next()); 
console.log(iterat.throw()); // error: Object is possibly 'undefined'. 
console.log(iterat.next()); 
console.log(iterat.next()); 
console.log(iterat.next()); 

誰でもスマートな解決法を知っていますか?私はこのリンクとは異なる何かによってスマートを意味します:https://github.com/Microsoft/TypeScript/issues/14431

答えて

0

残念ながら、throw and return are both optional in Iterator。発電機は、より具体的な何かをするのではなく、イテレータを返すために持っている理由

interface Iterator<T> { 
    next(value?: any): IteratorResult<T>; 
    return?(value?: any): IteratorResult<T>; 
    throw?(e?: any): IteratorResult<T>; 
} 

正直なところ、私は理解していません。結局のところ、GeneratorFunctionsは常に何かを返すので、常にエラーが出る可能性があります。 I filed a suggestion for TypeScript here.一方

、あなたが行うことによってこの問題を回避することができます

iterat.throw!() 
関連する問題