【问题标题】:Object is possibly 'undefined' when init a variable Typescript初始化变量 Typescript 时,对象可能是“未定义”
【发布时间】:2020-10-17 20:20:13
【问题描述】:

我的应用中有一个这样的组件:

@Component({
  selector: 'app-payment-intent',
  templateUrl: './payment-intent.component.html',
  styleUrls: ['./payment-intent.component.css']
})
export class PaymentIntentComponent implements OnInit {

  static = false;
  @ViewChild(StripeCardComponent, this.static) card: StripeCardComponent;

但是,当我尝试编译应用程序时,我得到了

Object is possibly 'undefined'

错误出现在变量static = false 中,导致@ViewChild(StripeCardComponent, this.static) card 尽可能接收变量undefined,但正如您所见,变量不是undefined,变量是在@ 中初始化的布尔值987654327@..

我能做些什么来解决这个问题?

谢谢!

【问题讨论】:

  • 您可以尝试将其定义为static: boolean = false;。但问题可能在于static 是保留字,因此您可能需要重命名变量。

标签: angular typescript undefined


【解决方案1】:

你可以参考Angular的Static Query Migration,它显示@ViewChild第二个参数是{ static: boolean }类型,所以你应该编辑你的:

@ViewChild(StripeCardComponent, { static: this.static }) card: StripeCardComponent;

或者直接分配更好,因为这个条件将在初始化时应用:

@ViewChild(StripeCardComponent, { static: false }) card: StripeCardComponent;

【讨论】:

    【解决方案2】:

    @ViewChild,在这种情况下,是一个装饰器。要理解这个问题,您需要了解装饰器的工作原理以及它们如何应用于方法。

    原码:

    function decorator(value?:any) {
      return function <T>(target: unknown, propertyKey: string, descriptor: TypedPropertyDescriptor<T>): void {
        console.log('value:', value);
      };
    }
    
    class Bar {
        @decorator(this)
        public foo():void {}
    }
    

    编译代码:

    // __decorate and __metadata declarations skipped
    
    function decorator(value) {
      return function (target, propertyKey, descriptor) {
        console.log('value:', value);
      };
    }
    
    class Bar {
      foo() { }
    }
    
    __decorate([
      decorator(this),
      __metadata("design:type", Function),
      __metadata("design:paramtypes", []),
      __metadata("design:returntype", void 0)
    ], Bar.prototype, "foo", null);
    

    编译这段代码后,你可以看到装饰器修改了原型类,而不是它的实例。因此,您传递给装饰器的参数“this.static”中的“this”指向没有上下文,因此它的值是未定义的。

    【讨论】:

    • 解释得很好。我觉得这个这个解释应该是TypeScript在文档中提供的,或者直接在错误信息中简明扼要的总结一下。
    猜你喜欢
    • 1970-01-01
    • 2016-02-24
    • 2013-07-04
    • 2019-02-21
    • 1970-01-01
    • 2012-03-25
    • 2015-07-04
    相关资源
    最近更新 更多