今日已更新 80 条资讯 | 累计 20052 条内容
关于我们

标签:#arrayfrom

找到 1 篇相关文章

AI 资讯

TypeScript TS2802 Error: Resolving Observer Pattern 'Set' Spread with Array.from Conversion

TypeScript Compile Error TS2802: Resolved with Observer Pattern by Converting Set Spread to Array.from If you're stuck implementing the observer pattern due to TypeScript compile error TS2802, this post might help. I resolved the issue with a simple conversion: changing Set spread to Array.from() . Attempts and Pitfalls While implementing the observer pattern, I encountered TypeScript compile error TS2802 when trying to spread a Set. Initially, I suspected the Set's type might be the problem, so I tried various approaches. class Observer { private subscribers = new Set < () => void > (); subscribe ( callback : () => void ) { this . subscribers . add ( callback ); } notify () { // TS2802 error occurs here for ( const callback of [... this . subscribers ]) { callback (); } } } When attempting to spread the Set into an array using [...this.subscribers] as shown above, TypeScript failed to recognize it properly, throwing an error similar to TS2802: Cannot find module '...' or its corresponding type declarations. . At first, I thought it was a library configuration issue and spent a considerable amount of time lost. The Cause In the end, the problem lay with the Set spread syntax itself. When TypeScript applies the ... spread operator to a Set, there were instances where it couldn't accurately infer the types internally. This issue can be more pronounced in certain versions or environments. The Solution To resolve this, I used the method of explicitly converting the Set spread to an array using Array.from() . class Observer { private subscribers = new Set < () => void > (); subscribe ( callback : () => void ) { this . subscribers . add ( callback ); } notify () { // Resolved by converting with Array.from for ( const callback of Array . from ( this . subscribers )) { callback (); } } } By using Array.from(this.subscribers) , TypeScript clearly recognizes the Set as an array, allowing the loop to execute correctly. The Outcome The TypeScript compile error TS2802 was cleanl

2026-06-13 原文 →