Type 'Object' is not assignable to type 'null'

5.5k views Asked by At

I'm getting this error, after I added a function called ngInit which will call the getCountries function in the Service class:

"Type 'Object' is not assignable to type 'null'"

import { Component, OnInit } from '@angular/core';
import {MessageService} from './message.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  title = 'Tour of Heroes';

  countryData = null;
  constructor(private api:MessageService) {}
  ngOnInit() {
    this.api.getCountries().subscribe((data)=>{
      this.countryData = data;
    });
  }

}
5

There are 5 answers

0
Robby Cornelissen On

Because of your countryData = null property initialization, TypeScript infers the type of countryData to be null. Assigning anything other than null to this property will result in the error you're seeing.

To fix, you can:

  1. Type the property as any:

    countryData: any = null;
    
  2. Define a type for your data, and set the property to be either that type or null:

    countryData: CountryDataType | null = null;
    
  3. Define a type for your data, set the property to be of that type, and mark it as optional (note that in this case the initial value is undefined instead of null):

    countryData?: CountryDataType;
    
0
Chathura Ishan On

You have declare the return type as null or turn off strictNullChecks in your tsconfig.

Change the type null as any.

0
Vignesh On

simple change to make it work is to change the type to any or provide a interface for country

countryData: any;

or as Robby

countryData:CountryDateType
0
Bujaq On

As You've initialized countryData with null, compiler compares new value to null type - it's the same as You would initialize it with String type and try to assign a Number type. If You need a one time solution, just use type casting.

this.countryData = data as any

instead of this.countryData = data

Hence: If You wish to make this field typeCheck immune just look at @Vignesh answer.

0
kathikeyan A On

you can try the following if you dont know the response type for the api call

countryData = <any><unknown>null;

if you know the type of response (say it is String) you can use,

countryData = <String><unknown>null;