gpt4 book ai didi

typescript - 如何使用 TypeScript 防止成员在构造函数中未定义?

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:53 24 4
gpt4 key购买 nike

我通过编写这样的类引入了一个错误:

class SomeClass {
private readonly item: string;

constructor(item: string) {
// bug, item is never assigned
}

public getInfo(): string {
return this.item; // always returns `undefined`
}
}

该项目从未分配,因此每次调用 getInfo() 都会返回 undefined。不过,此代码已成功转译。

我当前项目的代码风格通过 tslint 的 no-parameter-properties 规则阻止使用简写构造函数,因此我不能这样做:

class SomeClass {
public constructor(private readonly item: string) {
}

public getInfo() {
return this.item;
}
}

由于我的 tsconfig 的 strictNullChecks 设置,我原以为 tsc 会抛出错误。

有没有办法让 typescript 检测到这个错误并将其编译标记为错误?

这是我当前的 tsconfig.json 编译器选项:

  "compilerOptions": {
"target": "ES6",
"lib": [
"es6",
"es2017",
"DOM"
],
"module": "commonjs",
"pretty": true,
"outDir": "dist",
"sourceMap": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
}

最佳答案

如果你有 tsc >=2.7.1,那么你要么在寻找 compiler options

--strict

Enable all strict type checking options. Enabling --strict enables --noImplicitAny, --noImplicitThis, --alwaysStrict, --strictNullChecks, --strictFunctionTypes and --strictPropertyInitialization.

因为它包含所有严格的规则集。

或者更具体的说

--strictPropertyInitialization

因为那个是为您的用例设计的:

Ensure non-undefined class properties are initialized in the constructor. This option requires --strictNullChecks be enabled in order to take effect.

使用该设置,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;
~~~~

关于typescript - 如何使用 TypeScript 防止成员在构造函数中未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53172520/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com