node.js表达错误TS2531:对象可能为“空”

时间:2020-10-05 17:11:52

标签: javascript node.js typescript socket.io

我正在将socket.ionodejs一起使用,并尝试通过该类的方法之一获取socketio实例。

项目文件夹结构:

enter image description here

我有以下代码:

app.ts

class App  {
  public app: express.Application;
  private PORT: number;
  private dbUrl = DB_URL as string;
  public IO = null;

  constructor(routes: any, port: any) {
    this.app = express();
    this.config();      
  }

  public listen = (): void => {
      const server = this.app.listen(this.PORT, () => {
        console.log(`Server is running on port ${this.PORT}`);
      });
      const io = socket(server);
      this.IO = io; <-- IO

  };
}

export default App;

server.ts

import App from "./app";

import Auth from "./Route/Auth";
import TwitterFeed from './Route/TwitterFeed';
import EconomicFeed from './Route/EconomicFeed';
require("dotenv").config();

const { PORT } = process.env;
const app = new App([new Auth(), new TwitterFeed(), new EconomicFeed()], PORT);
app.listen();
export default app; <-- export app here

TwitterFeed

import app from '../../server';
class TwitterFeed {
    .
    .
    .
    private streamPublicTweets = (request:Request, response:Response)=>{      
        // establish socket connection
        console.log('app', app.IO); <-- this is displayed with no error
        const io = app.IO 
        io.on('connection', (socket: any) => {
          console.log('socket connected');
          streamTweets(this.T, socket)
        });    
    }
}

TwitterFeed类中,我尝试使用一种方法访问app导入。 在控制台中,没有错误的输出: enter image description here

但是在第io.on()行中,出现此错误: enter image description here

我在这里想念什么?

0 个答案:

没有答案