Purpose of declare keyword in TypeScript

前端 未结 5 1076
忘了有多久
忘了有多久 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 21:52

    From Typescript docs:

    Typescript - Working with Other JavaScript Libraries

    To describe the shape of libraries not written in TypeScript, we need to declare the API that the library exposes. Because most JavaScript libraries expose only a few top-level objects, namespaces are a good way to represent them.

    We call declarations that don’t define an implementation “ambient”. Typically these are defined in .d.ts files. If you’re familiar with C/C++, you can think of these as .h files. Let’s look at a few examples.

    Ambient Namespaces

    The popular library D3 defines its functionality in a global object called d3. Because this library is loaded through a tag (instead of a module loader), its declaration uses namespaces to define its shape. For the TypeScript compiler to see this shape, we use an ambient namespace declaration. For example, we could begin writing it as follows:

    D3.d.ts (simplified excerpt)

    declare namespace D3 {
        export interface Selectors {
            select: {
                (selector: string): Selection;
                (element: EventTarget): Selection;
            };
        }
        // (...)
    }
    

提交回复
热议问题