Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript assign null to a type don't trigger error

Can anyone explain me, please, why this code dont trigger an error?

import { Injectable } from '@angular/core';

interface Animal{
  name: string;
}

@Injectable()
export class AnimalService {
  lion: Animal = null;
  constructor() {}
  get(){
   return this.lion;
 }
}
like image 607
Whisher Avatar asked Jul 24 '26 14:07

Whisher


1 Answers

You have to set "strictNullChecks": true in your tsconfig.json for it to throw error when you do lion: Animal = null;.

See the documentation for strictNullChecks compiler flag:

In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).

Also see: https://ariya.io/2016/10/typescript-2-and-strict-null-checking

like image 197
Saravana Avatar answered Jul 27 '26 06:07

Saravana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!