Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript - return an empty array without declaring a local variable

Tags:

typescript

I have a piece of code that looks like this:

let emptyArray: string[]
    if (context == null) 
        return emptyArray

Is there no way to do this:

    if (context == null) 
        return new string[]
like image 437
lanierhall Avatar asked Aug 14 '26 11:08

lanierhall


2 Answers

You can also type assert what you return so that the compiler knows that you are returning a string[] and not just an array. If you don't want to define it anywhere else.

if (context == null) 
    return [] as string[];

And of course, an empty array is always a valid value for any kind of array.

like image 84
Alex Avatar answered Aug 16 '26 02:08

Alex


It's not completely clear what you want because there's no context, for example who returns the empty array and who's getting this result, but it's easy to just do:

function fn(context: any): string[] {
    if (context == null) {
        return [];
    }
    ...
}
like image 42
Nitzan Tomer Avatar answered Aug 16 '26 00:08

Nitzan Tomer



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!