Readonly property has no initializer and is not definitely assigned in the constructor

huangapple go评论62阅读模式
英文:

Readonly property has no initializer and is not definitely assigned in the constructor

问题

The issue you're facing is related to TypeScript's strict null checking. To fix it correctly, you can update your constructor like this:

class myProps {
  public readonly val1: boolean;

  constructor(val1: boolean = true) {
    this.val1 = val1;
  }
}

This change ensures that val1 is initialized in the constructor and provides a default value of true if it's not explicitly provided when creating an instance of the class.

英文:

Creating a class like:

class myProps {
  public readonly val1: boolean;

  constructor(val1?: boolean) {
    val1 != undefined ? this.val1 = val1 : val1 = true;
  }
}

I would expect that his is ok, as inside the constructor (unlike the error claims) val1 is always set to a value. however I get this error (inside the IDE) on the readonly attribute val1:

> Property 'val1' has no initializer and is not definitely assigned in
> the constructor.

Why is this and how would I fix it correctly?

答案1

得分: 1

你第二次分配val1前漏掉了this,所以你在另一个分支上给本地变量赋值,而不是实例变量,因此会出现错误,指出它未始终初始化。 应该是:

class myProps {
  public readonly val1: boolean;

  constructor(val1?: boolean) {
    val1 != undefined ? this.val1 = val1 : this.val1 = true;
  }
}
英文:

You are missing a this before your second assignment of val1, so you're assigning to the local variable in the other branch, not the instance variable, hence the error that it is not always initialized. It should be

class myProps {
  public readonly val1: boolean;

  constructor(val1?: boolean) {
    val1 != undefined ? this.val1 = val1 : this.val1 = true;
  }
}

答案2

得分: 0

你的构造函数中存在语法错误(具体来说是在你的三元操作符赋值中)。

赋值可以如下所示:


class myProps {
  public readonly val1: boolean;

  constructor(val1?: boolean) {
    this.val1 = typeof val1 === 'boolean' ? !!val1 : true;
  }
}

var instance = new myProps(false);

console.log(instance.val1); //应该打印false,因为传递给构造函数的参数是false


英文:

There is syntax error in you constructor (specifically in your ternary operator assignment).

The assignment could be the following:


class myProps {
  public readonly val1: boolean;

  constructor(val1?: boolean) {
    this.val1 = typeof val1 === 'boolean' ? !!val1 : true;
  }
}

var instance = new myProps(false);

console.log(instance.val1); //should print false, as passed parameter to constructor


huangapple
  • 本文由 发表于 2023年5月7日 19:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76193542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定