Purpose of declare keyword in TypeScript

前端 未结 5 1083
忘了有多久
忘了有多久 2020-11-29 21:21

What is the purpose of the declare keyword?

type Callback = (err: Error | String, data: Array) => void;
5条回答
  •  日久生厌
    2020-11-29 22:07

    Here is a real world example.

    I have a TypeScript React app that uses the Webpack Hot Middleware. The Webpack Hot Middleware is not written in TypeScript, but in good old-fashioned JavaScript. So it has no type declarations that the TypeScript compiler can check against.

    When I run my code, the object module from the Webpack Hot Middleware exists, and I can console.log it despite it being good old-fashioned JavaScript hiding in my fancy new TypeScript React app.

    The module object also has keys, such as module.hot, and the keys can have values. But the TypeScript design time compiler (in VSCode at least) draws a red squiggly under it saying property 'hot' does not exist. But it does exist!

    To make the TypeScript compiler agree, declare it like this:

    declare let module: any
    

    The existing module object, now has a type of any, which makes the TypeScript compiler happy now, red squiggly gone and now I can continue to compile and write my other code.

    If you remove the keyword declare, and just write let module: any, it will not compile, instead saying that 'module' already exists. That's what "ambient" in the accepted answer means.

提交回复
热议问题