代码之家  ›  专栏  ›  技术社区  ›  Thomas David Kehoe

为什么我的对象在我记录时是“未定义的”?

  •  0
  • Thomas David Kehoe  · 技术社区  · 5 年前

    我做了一个 StackBlitz

    我跟着 TypeScript Handbook 对于对象类型:

    person: { name: string; age: number }
    

    Button clicked!
    42
    { foo: undefined; bar: undefined }
    { foo: 42; bar: true }
    

    但我得到的却是:

    Button clicked!
    42
    undefined
    ERROR Error: cannot set property 'foo' of undefined
    

    发生了什么?

    app.component.html

    <button (click)="clickMe(42)">Click me!</button>
    

    app.component.ts

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
    })
    export class AppComponent  {
      myObject: { foo: number; bar: boolean };
    
      clickMe(value) {
        console.log("Button clicked!");
        console.log(value);
        console.log(this.myObject);
        this.myObject.foo = value;
        this.myObject.bar = true;
        console.log(this.myObject);
      }
    }
    

    enter image description here

    1 回复  |  直到 5 年前
        1
  •  1
  •   Alejandro Camba    5 年前

    你的属性是未定义的,你只定义了它的类型,而没有定义它的值,这就是为什么当你试图给它的属性赋值时,你会得到错误。在构造函数中初始化它这个.myObject={foo:null,bar:null}或者您可以将属性设置为可选的并按如下方式初始化它这个.myObject= {}

    推荐文章