Sandro Rey
Sandro Rey

Reputation: 2999

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

I have created these types

export type Maybe<T> = T | null;
hostels: Array<Maybe<Hostel>>;
hostel: Hostel;


if (hostels && hostels.length > 0) {
            hostel = hostels[0];
}

but I have this compilation error:

Type 'null' is not assignable to type 'Hostel'.

Upvotes: 1

Views: 804

Answers (1)

A fast answer is to disable strictNullChecks in your tsconfig.json (or command line, or whatever you are using to configure typescript) so you can assign null to almost everything, even without needing to set the typings to null. Is like having all definitions include | null implicitly.

If you still require strictNullChecks enabled, then the types must match. The same way a string variable can only receive string types, hostel must be the same type as Maybe<Hostel>, which is Hostel | null, so:

export type Maybe<T> = T | null;
hostels: Array<Maybe<Hostel>>;
hostel: Hostel | null;

if (hostels && hostels.length > 0) {
    hostel = hostels[0];
}

Upvotes: 1

Related Questions