Consider the following TypeScript code using an ambient declaration. What will be the output when running the compiled JavaScript?
declare const greeting: string; console.log(greeting);
Ambient declarations tell TypeScript about variables that exist elsewhere but do not create them.
The declare keyword only tells TypeScript that a variable exists. It does not create the variable in JavaScript. So at runtime, if greeting is not defined globally, it causes a ReferenceError.
Why do developers use ambient declarations in TypeScript?
Think about how TypeScript knows about variables from other scripts or libraries.
Ambient declarations let TypeScript know about variables, functions, or types that are defined elsewhere (like in a JavaScript library) so it can type-check code that uses them.
Examine this TypeScript code snippet. What error will it produce?
declare module 'myLib' { export function greet(name: string): string; } import { greet } from 'myLib'; console.log(greet(123));
Check the argument type passed to the function versus the declared type.
The ambient declaration says greet expects a string argument. Passing a number (123) causes a type error during compilation.
Given this ambient declaration and usage, why does the code fail at runtime?
declare var config: { apiKey: string }; console.log(config.apiKey);
Ambient declarations do not create variables in the output JavaScript.
The declare var tells TypeScript the variable exists but does not create it. If config is not defined in the actual JavaScript environment, accessing config.apiKey causes a runtime error.
Given this ambient declaration extending the global Window interface, how many new properties are added to window?
declare global {
interface Window {
appVersion: string;
isLoggedIn: boolean;
logout(): void;
}
}
console.log(Object.keys(window).includes('appVersion'));Ambient declarations describe types but do not create actual properties in JavaScript.
Ambient declarations extend TypeScript's type system but do not add properties to objects at runtime. So window does not have these properties unless they are set elsewhere.