简体   繁体   English

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

[英]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.

相关问题 如何从构造函数中访问静态成员 - How to access a static member from within a constructor 如何防止`必需<T> ` 在打字稿中使用 --strictNullChecks 时从类型中删除“未定义” - How to prevent `Required<T>` in typescript from removing 'undefined' from the type when using --strictNullChecks Typescript类属性在构造函数中初始化,而在成员函数中未定义 - Typescript class property initialized in constructor and undefined in member function 如何防止在 TypeScript 类型和接口中使用“any” - How to prevent "any" from being used in TypeScript types and interfaces 如何设置构造函数中未知的打字稿成员变量 - how to set typescript member variables that are unknown in constructor 如何防止 typescript 抱怨属性可能未定义 - How can I prevent typescript from complaining that a property can be undefined 在 TypeScript 中,如何防止在派生类上调用方法? - In TypeScript, how to prevent a method from being called on derived class? Typescript:尽管在构造函数中已初始化,但变量值未定义 - Typescript: variable value undefined despite being initialized in constructor 防止“ this”被重写为TypeScript编译 - Prevent “this” from being rewritten TypeScript compilation 成员在TypeScript中未定义 - member is undefined in TypeScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM