7

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;
 }
}
1
  • By default in JavaScript(and Typescript) any field can have the value null or undefined, have a look at stricktNullCheck. Commented Aug 13, 2017 at 8:33

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

5 Comments

So what's the best options put the flag to false or set it to true and using a syntax like const lunchBox: Nullable<Food>[] = [];
That depends on your requirements. I personally turn on strictNullChecks and use variable: Type | null for specific cases where nulls can be allowed.
It just becomes a nightmare because now you have to typecast every time you set a value. You cannot set it to a string value because the compiler will say it doesn't match the defined type string | null
@Spock use the non null assertion operator: !. E.g someNonNullMethod(someNullabeValue!)
@mdsimmo yep, it just feels like a hack :) .. but yeah good point, thanks
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.