Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: Generic function return null

Tags:

typescript

I am having the next function in typescript:

In c# you have something like default(T) but in typescript I dont know.

public Base {
...
}


public Get<T extends Base>(cultura: string): T[] 
{

    let res = null;

    try
    {

    }
    catch (ex)
    {
        throw ex;
    }

    return res;
}

I want to return a null but I get an error. If I assign it in a variable the null and return the variable happens the same error.

Message is: The 'null' type can not be assigned to the type T[].

The error is:

enter image description here

How can I do it in TypeScript?

like image 765
David Avatar asked Sep 09 '18 16:09

David


1 Answers

You have strict null checks on. This means you cannot assign null to a variable (or return value) unless you’ve said that is a possibility. So either turn strict null checks off (strictNullChecks: false in tsconfig.json) or change the return type to T[] | null. Or, better yet, return an empty array and not null.

like image 78
Pace Avatar answered Sep 29 '22 21:09

Pace