Type declare keyword assignment in TypeScript

What is the purpose of the declare keyword?

 type Callback = (err: Error | String, data: Array<CalledBackData>) => void; 

against.

 declare type Callback = (err: Error | String, data:Array<CalledBackData>) => void; 

Cannot find documents that explain the purpose of the declare keyword in TS.

+20
typescript
source share
3 answers

The first result I get from google suggests:

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

http://blogs.microsoft.co.il/gilf/2013/07/22/quick-tip-typescript-declare-keyword/

+5
source share

Here is an example from the real world.

I have a TypeScript React application that uses the hot Webpack middleware. Webpack Hot Middleware is not written in TypeScript, but in the good old JavaScript. Thus, it does not have type declarations with which the typescript compiler can check.

Therefore, when I run my code, the module object from Webpack Hot Middleware exists, and I can also install it console.log, despite the fact that it is old-fashioned JavaScript that is hidden somewhere in my new trendy TypeScript React application.

The module object also has keys, such as 'module.hot', and the keys can make a difference. But the TypeScript design time compiler in VSCode at least draws a red wavy text under it, saying property 'hot' does not exist

but it exists, I say.

To agree with the TypeScript compiler, declare this as

declare let module: any

the existing module object is now of type any , which makes the TypeScript compiler happy, red disappears, and now I can continue to compile and write my innovative code that will change the world.

Also, if you delete the declare keyword and simply write let module: any , it will not compile, saying that 'module' already exists . So I think that means ambient.

+10
source share

The delcare keywords are used when you import some library that doesn’t have any declaration files like * .d.ts

after that vs eslint does not check the syntax and context, it will allow you, if you are using the tsc compiler by default, to skip the good reason for declaring a syntax error

0
source share

All Articles