Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a `declare` keyword in ES6/7?

Recently I've been studying ES6, and that lead to me using Babel a lot. Being the curious type, I started looking at the Babel Github repository to know how they built this awesome tool, and know if I can somehow contribute.

However, I came across this file, and it has things like declare class BabelNodeSourceLocation {} written all over it, and the file ends with .js.

This got me very confused, and I am now wondering whether there's a declare keyword in JavaScript that I didn't know of, or is this just a Babel-specific syntax? All my Google searches resulted in nothing.

Update: Putting the code in the Babel REPL resulted in nothing. Babel just ignored the code and did not produce any equivalent ES5 output. It also did not throw any error.

like image 606
Kizer Avatar asked Feb 23 '16 16:02

Kizer


People also ask

How do I declare variables in ES6?

A variable can be initialized at any time before its use. The ES6 syntax used the keyword var to declare a variable. In ES5, we declare the variable like this: var x //Declaration of a variable by using the var keyword.

What is declare keyword in JS?

The declare keyword in TypeScript is used for the Ambient declaration of variables or for methods. Ambient Declarations is like an import keyword.

What are the two new keywords for declaring variables in ES6?

Local variable: When we declare a variable inside of a function. But, ECMAScript 2015 (ES6) introduced two new keywords let and const and these two keywords provide Block Scope in JavaScript.

How many ways can you declare variables in ES6?

Now, with ES6, there are three ways of defining your variables: var , let , and const .


2 Answers

and the file ends with .js.

That doesn't mean a lot these days :-)

I am wondering whether there's a declare keyword in JavaScript that I didn't know of

No, there is not.

Or is this just a Babel-specific syntax?

No. It is a type declaration file for the Flow typechecker.

like image 143
Bergi Avatar answered Oct 20 '22 23:10

Bergi


With Flow, you can declare a global class that allows you to reference the class type anywhere in your project. This has no affect on runtime code and won't affect babel output.

An example from the docs:

declare class URL {
  constructor(urlStr: string): URL;
  toString(): string;

  static compare(url1: URL, url2: URL): boolean;
};

And then in your project you can reference URL as a class type.

Similarly, you can declare other global Types, Modules, Functions, Variables. A good way to keep them organized.

like image 45
Mark Swardstrom Avatar answered Oct 20 '22 23:10

Mark Swardstrom