是否可以防止闭包捕获TypeScript中的外部变量?

假设我有以下Typescript代码:

const x = 123
const f = () => x 

Is it possible to do something such that Typescript compiler can produce an error/warning during compile time saying that function f is capturing an external variable x ?

P / S:我只是在寻找这种机制的技术可能性,为什么我不应该这样做的解释将不被接受。

评论
  • MS女人
    MS女人 回复

    I'd write f in a separate file, that way no other variables from the original file will be lexically visible. This work just fine in Javascript too:

    // main.ts
    import { f } from './f'
    const x = 123;
    // do stuff with f and x
    
    // f.ts
    export const f = () => {
      console.log('running f');
      // trying to reference x here (or anything from the original file)
      // will throw a TS error
    };