Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Meaning of the “at” (@) Prefix on NPM Packages

The @ prefix means that the package is a scoped package.

That means the work with the @ prefix is the namespace of the package.

For instance, @angular/http is has angular as the namespace.

Scoped packages don’t show up in public search.

Many of them are created as private packages.

Write an Inline if Statement in JavaScript

We can write an inline if statement by using the ? in Javascript.

For instance, we can write:

(a < b) ? 'bigger' : 'smaller'

a < b is the boolean expression.

If it’s true , then we return 'bigger' .

Otherwise, we return 'smaller' .

Interface Type Check with Typescript

We can check if an object matches an interface with the in operator.

For instance, we can write:

interface A {
  name: string;
}

Then we can create the following function:

function instanceOfA(object: any): object is A {
  return 'name' in object;
}

We make the return type of instanceOfA object is A . This way, we return whether the object matches an interface.

Then we can call the function as follows:

if (instanceOfA(obj)) {
  //...
}

Handle Newlines in JSON

If we have newline characters in our JavaScript object, then we need to escape them in the JSON string.

Otherwise, we would get an unterminated string literal error.

For instance, instead of writing:

const data = '{ "count" : 1, "foo" : "text\n\n" }';

We write:

const data = '{ "count" : 1, "foo" : "text\\n\\n" }';

#web-development #programming #software-development #javascript #technology

JavaScript Tips — TypeScript Interface Checks, Showing/Hiding Elements
1.20 GEEK