1. Welcome and Icebreaker:
- If you could describe the shape of any tool or object you use, what would you choose?
2. Outline the Session:
- We’ll learn about ambient declarations and declaration files in TypeScript.
- Learning Outcomes: Understand how to describe the shape of existing JavaScript code for type safety.
- Let’s declare some types!
3. Concept Explanation:
- Ambient Declarations use the
declare keyword to describe code that exists elsewhere (e.g., in JavaScript libraries).
- Declaration Files (
.d.ts) contain only type declarations, not implementations.
- Useful for using third-party JavaScript libraries in TypeScript projects.
- Syntax:
declare function greet(name: string): void;
// In a .d.ts file
declare module 'my-library';
- TypeScript uses declaration files to provide type information for JavaScript code.
4. Live Coding Demonstration:
// In a .d.ts file
declare function add(a: number, b: number): number;
// Usage in TypeScript
add(2, 3); // OK, even if implementation is in JS
// Declaring a global variable
declare const VERSION: string;
console.log(VERSION);
// Declaring a module
declare module 'my-library' {
export function doSomething(): void;
}
5. Tasks:
- Short Exercise:
- Write a declaration file for a function
sum(a: number, b: number): number.
- Write a declaration for a global variable
APP_NAME (string).
- Write a module declaration for a library
cool-lib with a function cool().