[英]How to prevent a member from being undefined within a constructor using TypeScript?
I have introduced a bug by writing a class like this:我通过编写这样的类引入了一个错误:
class SomeClass {
private readonly item: string;
constructor(item: string) {
// bug, item is never assigned
}
public getInfo(): string {
return this.item; // always returns `undefined`
}
}
the item is never assigned and hence each call to getInfo()
would return undefined
.该项目永远不会被分配,因此每次调用
getInfo()
都会返回undefined
。 This code transpiles successfully though.但是,此代码成功转译。
The code style of my current project is preventing the usage of the short-hand constructor via tslint's no-parameter-properties
rule, and hence I cannot do:我当前项目的代码风格通过 tslint 的
no-parameter-properties
规则阻止使用简写构造函数,因此我不能这样做:
class SomeClass {
public constructor(private readonly item: string) {
}
public getInfo() {
return this.item;
}
}
I was expecting tsc to throw an error due to the strictNullChecks
setting of my tsconfig.由于我的 tsconfig 的
strictNullChecks
设置,我期望 tsc 抛出错误。
Is there a way to make typescript detect this bug and mark its compilation as an error?有没有办法让打字稿检测到这个错误并将其编译标记为错误?
This is my current tsconfig.json
compilerOptions:这是我当前的
tsconfig.json
compilerOptions:
"compilerOptions": {
"target": "ES6",
"lib": [
"es6",
"es2017",
"DOM"
],
"module": "commonjs",
"pretty": true,
"outDir": "dist",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
}
If you have tsc >=2.7.1, then you are either looking for the compiler options如果你有 tsc >=2.7.1,那么你要么在寻找编译器选项
--strict
Enable all strict type checking options.
启用所有严格的类型检查选项。 Enabling
--strict
enables--noImplicitAny
,--noImplicitThis
,--alwaysStrict
,--strictNullChecks
,--strictFunctionTypes
and--strictPropertyInitialization
.启用
--strict
启用--noImplicitAny
、--noImplicitThis
、--alwaysStrict
、--strictNullChecks
、--strictFunctionTypes
和--strictPropertyInitialization
。
as that contains all the strict rulesets.因为它包含所有严格的规则集。
Or more specifically for或者更具体地说
--strictPropertyInitialization
as that one is designed for your use-case:因为那个是为您的用例设计的:
Ensure non-undefined class properties are initialized in the constructor.
确保在构造函数中初始化非未定义的类属性。 This option requires
--strictNullChecks
be enabled in order to take effect.此选项需要启用
--strictNullChecks
才能生效。
With that setting, tsc will now throw:使用该设置,tsc 现在将抛出:
src/SomeClass.ts:2:22 - error TS2564: Property 'item' has no initializer and is not definitely assigned in the constructor.
2 private readonly item: string;
~~~~
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.