打字稿忽略静态变量,并认为它是正确的类型安全?

时间:2019-02-24 17:47:24

标签: typescript

所以我有以下代码

export class X {
  static foo: {
    bar: number;
  };

}

const bar = X.foo.bar

而且看来打字稿不能检查我的X.foo是否可能不确定。

它会正确检查foo是否不是静态成员。

这是我的tsconfig.json(如果需要的话)。

{
  "compilerOptions": {
    "types": ["node"],
    "target": "esnext",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    "strict": true,                           /* Enable all strict type-checking options. */
    "baseUrl": "./src",                       /* Base directory to resolve non-absolute module names. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
  },
  "exclude": [
    "dist",
    "node_modules",
    "__test__"
  ]
}

是错误,还是类对象中有魔术使得无法对其进行检查?

tsconfig中是否有一个选项可以打开以检查X.foo是否实际上未定义?

1 个答案:

答案 0 :(得分:2)

这看起来像reported issue(或者可能是different but still known issue)。在TypeScript 2.7中,引入了--strictPropertyInitialization编译器标志,但它似乎仅作用于实例属性。我希望它也可以作用于静态属性,但是也许期望不是通用的……链接的问题被归类为“建议”而不是“错误”。无论如何,我想您可以转到GitHub并给相关问题一个,和/或解释您的用例(如果它特别引人注目且尚未提及)。

希望有帮助。祝你好运!