What are ambient declarations

后端 未结 1 618
独厮守ぢ
独厮守ぢ 2020-12-31 01:12

I\'ve been seeing a lot using articles mentioning ambient declarations. For example this article. What are they? Can somebody provide an example? Is an ambient

相关标签:
1条回答
  • 2020-12-31 02:00

    Yes, ambient declarations let you tell the compiler about existing variable/functions/etc.

    For example let's say that in your web page you're using a library that adds a global variable, let's say that it's name is ON_READY and it is a reference to a function.
    You need to assign a function to it so you'll do something like:

    ON_READY = () => {
        console.log("ready!");
        ...
    };
    

    The compiler will complain that:

    Cannot find name 'ON_READY'

    So you use an ambient declaration to inform the compiler that this variable exists and what it's type is:

    declare var ON_READY: () => void;
    

    Now it won't complain about not finding it.


    Edit

    When using the declare keyword it is always ambient, just like it says in the article you linked to:

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

    Non-ambient declarations are just normal variable/function declarations:

    let x: number;
    const y = "string";
    var a = () => { console.log("here"); }
    
    0 讨论(0)
提交回复
热议问题