Whisher
Whisher

Reputation: 32796

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;
 }
}

Upvotes: 7

Views: 6816

Answers (2)

Mohamed A M-Hassan
Mohamed A M-Hassan

Reputation: 443

use variable: Type | null for specific cases where nulls can be allowed.

ex: name:string| null

I personally turn on strictNullChecks and use the specific cases.

Upvotes: 3

Saravana
Saravana

Reputation: 40672

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

Upvotes: 8

Related Questions