BunnyStrider BunnyStrider - 1 year ago 144
TypeScript Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download