[Typescript] Difference between return a variable or Object directly


export interface TwitterResolverContext {
  db: Db;
  dbTweetCache: Record<string, DbTweet>;
  dbUserCache: Record<string, DbUser>;
  dbTweetToFavoriteCountMap: Record<string, number>;
}

So the reason first version Typescript complains but second version not is that, it is possible people do:

    context: (): TwitterResolverContext => {
      const val = {
        db,
        dbTweetCache: {},
        dbUserCache: {},
        dbTweetToFavoriteCountMap: {},
        somethingelse: {},
      };
      val.somethingelse = ...;
      return val;
    },

so modify `somethingelse` before return it. But for first version is not possible:

    context: (): TwitterResolverContext => ({
      db,
      dbTweetCache: {},
      dbUserCache: {},
      dbTweetToFavoriteCountMap: {},
      somethingelse: {},
    }),

 

 

posted @ 2022-07-08 15:56  Zhentiw  阅读(24)  评论(0编辑  收藏  举报