7

Whenever tsc generates d.ts files, it includes declare word there, like this:

export declare class Moment {
    name: string;
}

Now, declare in ts files is used to say to tsc that no js should be generated for the type with declare. So it makes sense in the ts files. However, no js is generated from d.ts files anyway, why use the word there?

I tried to remove declare word from the above code:

export class Moment {
    name: string;
}

and it worked the same.

I've found the following here:

If a file has the extension .d.ts then each root level definition must have the declare keyword prefixed to it. This helps make it clear to the author that there will be no code emitted by TypeScript. The author needs to ensure that the declared item will exist at runtime.

So is it the only purpose of the declare in d.ts files?

Plese note, this is not the same question as this one, as my question is about using declare in d.ts files, not ts files.

Community
  • 1
  • 1
Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

2 Answers2

0

Both ".d.ts" files and ".ts" are processed by the same transpiler. And keywoard meaning are the same. According to the documentation and the article:

The declare keyword is used for ambient declarations where you want to define a variable that may not have originated from a TypeScript file.

The declare keyword makes transpiler does not produce any real JavaScript code and allows to use "declared" object in other TypeScript files.

TSV
  • 7,538
  • 1
  • 29
  • 37
  • 3
    This does not make sense, because `.d.ts` files *never* produce any JS code -- it's a "typings" file and is only used to inform the compiler about the shape of types. `.d.ts` cannot contain implementations, so `declare` is redundant there. – Coderer Apr 30 '18 at 08:15
0

It's pretty simple.
when you want to export a declaration of variable or function you have two ways to do that:

  1. you can create a variable or a function in one line and after that you can export it in a new line.
    To do that you need first "declare" the variable or the function, after that you can export it.
    for example:

declare class Moment {
    name: string;
}

export Moment;
  1. you can export it in one line without declaring it first. for example:

export class Moment {
    name: string;
}
tn2000
  • 642
  • 1
  • 8
  • 13