1
votes

I am using angular to built this app using this example from "https://coursetro.com/posts/code/171/Angular-7-Tutorial---Learn-Angular-7-by-Example".
Its an exact code but I am still getting an error for "user:Object"

How can I fix this error?

error TS2564: Property 'users' has no initializer and is not definitely assigned in the constructor.

12 users: Object; ~~~~~

Here is the exact code as per website:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
  //h1Style:boolean = false;

  users: Object;

  constructor(private data: DataService) { }

  ngOnInit(): void {
    this.data.getUsers().subscribe(data => {
        this.users = data
        console.log(this.users);
      }
    );
  }


}

My Angular based on ng version: Angular CLI: 11.1.2

Node: 14.15.4

OS: win32 x64

Angular: 11.1.1

... animations, common, compiler, compiler-cli, core, forms

... platform-browser, platform-browser-dynamic, router

Ivy Workspace: Yes

Package Version


@angular-devkit/architect 0.1101.2

@angular-devkit/build-angular 0.1101.2

@angular-devkit/core 11.1.2

@angular-devkit/schematics 11.1.2

@angular/cli 11.1.2

@schematics/angular 11.1.2

@schematics/update 0.1101.2

rxjs 6.6.3

typescript 4.1.3

1
Try lowercase object...MikeOne
same error even with lowercase objectuser244394
It isn't an error per se, more of a Typescript warning that you're not initializing this property, which as a result could be undefined at runtime. You can ignore it as the code should compile as-is.alcfeoh
sorry still getting error based on the example tutorial. it wont let me run with user:Object. if i remove it runs fineuser244394

1 Answers

3
votes

As @alcfeoh pointed out in the comments, you are getting this error because you are defining a variable but not declaring a value for it. The short answer is if you don't want to declare a value, then... just bang it:

users!: Object;

The reason why typescript throws this error is to prevent the following:

someNumber: number;

If there is no declaration included then the value of someNumber will be undefined even though we have explicitly not listed this type as someNumber: number | undefined;. But in many other languages, someNumber would receive a default value like 0. However that is not how Javascript works. If in this scenario you were to do someNumber + 1 the result would be null.