Home > other >  For what reason stack property is optional in Error?
For what reason stack property is optional in Error?

Time:01-13

In an Error, the property stack is optional. However, when I throw a new Error('myError') or when I have a generic error thrown during the execution of my script, I always get the stack. According to the browser, the stack is not the same but I is not undefined.

  • I was wondering in which case it was possible to have an undefined stack?

CodePudding user response:

The stack property is not defined by the JavaScript specification (yet). So a compliant JavaScript implementation could well not have a stack property on Error instances. Most do nowadays (certainly the big three: V8, SpiderMonkey, and JavaSciptCore), but it's not standardized (yet), so they don't have to.

In an Error, the property stack is optional.

I'm guessing you're referring to TypeScript's type information for Error:

interface Error {
    stack?: string | undefined;
}

Since most JavaScript engines do provide a stack property of type string even though it's not defined by the specification, making it optional with the type string | undefined is a pragmatic choice (the TypeScript project team are notoriously pragmatic). So rather than leave it out entirely, they acknowledge the common practice.

I was wondering in which case it was possible to have an undefined stack?

I think it's unlikely you'd have an undefined stack on an Error instance on implementations that support it (more likely "" if no stack information is available, but I don't recall seeing a blank stack). That said, there's likely a reason TYpeScript's types define it as stack?: string | undefined and not stack?: string.

  • Related