lanierhall
lanierhall

Reputation: 550

Typescript - return an empty array without declaring a local variable

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[]

Upvotes: 2

Views: 16995

Answers (3)

Alex
Alex

Reputation: 14493

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.

Upvotes: 10

peterholcomb
peterholcomb

Reputation: 84

Maybe I don't understand your question, but this seems to be valid typescript for me in my editor:

getValue(context): Array<String> {
    if(context==null) {
      return [];
    }
}

Upvotes: 2

Nitzan Tomer
Nitzan Tomer

Reputation: 164129

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 [];
    }
    ...
}

Upvotes: 3

Related Questions