Bird
Raised Fist0
Typescriptprogramming~10 mins

Writing custom declaration files in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Writing custom declaration files
Identify JS module without types
↓
Create .d.ts file
↓
Write declarations: types, interfaces, functions
↓
Save and include in project
↓
Use types in TypeScript code
↓
Compiler checks types using declarations
↓
End
You find a JavaScript module without types, create a .d.ts file declaring its types, then use those types in your TypeScript code for type checking.
Execution Sample
Typescript
declare module "myLib" {
  export function greet(name: string): string;
  export interface User {
    id: number;
    name: string;
  }
}
This declaration file tells TypeScript about the 'myLib' module's function and interface so you can use them with type safety.
Execution Table
StepActionCode EvaluatedResult
1Create declaration filedeclare module "myLib" { ... }Module 'myLib' declared with types
2Declare functionexport function greet(name: string): string;Function 'greet' expects a string and returns a string
3Declare interfaceexport interface User { id: number; name: string; }Interface 'User' with id and name properties defined
4Save filemyLib.d.ts savedTypes available for TypeScript compiler
5Use in codeimport { greet, User } from "myLib";TypeScript recognizes types from declarations
6Call functiongreet("Alice")Type checked: argument is string, return is string
7Create User objectconst user: User = { id: 1, name: "Bob" };Object matches declared interface
8ExitNo errorsTypeScript compilation succeeds
💡 All declarations are recognized and used for type checking, no errors found
Variable Tracker
VariableStartAfter Step 6After Step 7Final
greetundefinedfunction greet(name: string): stringfunction greet(name: string): stringfunction greet(name: string): string
Userundefinedinterface Userinterface Userinterface User
userundefinedundefined{ id: 1, name: "Bob" }{ id: 1, name: "Bob" }
Key Moments - 3 Insights
Why do we need a separate .d.ts file for a JavaScript module?
Because JavaScript files don't have type information, the .d.ts file tells TypeScript what types exist so it can check your code. See execution_table step 1 and 4.
What happens if the declared types don't match the actual JavaScript implementation?
TypeScript trusts the declaration file, so mismatches can cause runtime errors. Declarations must accurately reflect the real code. See execution_table step 6 and 7 for usage.
Can you declare multiple types inside one module declaration?
Yes, you can declare functions, interfaces, types, and more inside the same module block. See execution_table steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what type is the parameter of the 'greet' function at step 2?
Anumber
Bboolean
Cstring
Dany
💡 Hint
Check the 'Code Evaluated' column at step 2 in the execution_table
At which step does the TypeScript compiler recognize the declared types for use in code?
AStep 3
BStep 5
CStep 7
DStep 1
💡 Hint
Look for when the code imports and uses the declarations, see 'Action' column
If you forget to save the .d.ts file, what will happen when you try to use the module in TypeScript?
ATypeScript will show errors about missing types
BTypeScript will find the types anyway
CThe code will run without any type checking
DThe module will be ignored completely
💡 Hint
Refer to the importance of step 4 'Save file' in the execution_table
Concept Snapshot
Writing custom declaration files (.d.ts):
- Use 'declare module "moduleName" { ... }' to describe a JS module
- Inside, declare functions, interfaces, types with proper signatures
- Save the .d.ts file in your project
- TypeScript uses these declarations for type checking
- Keeps JS modules safe and typed in TS projects
Full Transcript
When you use a JavaScript module without built-in types, you create a custom declaration file with a .d.ts extension. This file uses 'declare module' syntax to tell TypeScript about the module's functions and interfaces. For example, you declare a function 'greet' that takes a string and returns a string, and an interface 'User' with id and name properties. After saving this file, TypeScript can check your code that imports and uses these types, preventing errors. The execution steps show creating the declarations, saving the file, and using the types in code with successful type checking. Key points include the need for accurate declarations and saving the file so TypeScript can find it.

Practice

(1/5)
1. What is the main purpose of writing a custom declaration file in TypeScript?
easy
A. To tell TypeScript about types in JavaScript or untyped libraries
B. To write JavaScript code that runs faster
C. To convert TypeScript code into JavaScript
D. To create new JavaScript functions

Solution

  1. Step 1: Understand the role of declaration files

    Declaration files provide type information about JavaScript code or libraries without types.
  2. Step 2: Identify the purpose in TypeScript

    This helps TypeScript check code and improve editor support by knowing types.
  3. Final Answer:

    To tell TypeScript about types in JavaScript or untyped libraries -> Option A
  4. Quick Check:

    Custom declaration files = type info for JS [OK]
Hint: Declaration files describe types for untyped JS code [OK]
Common Mistakes:
  • Thinking declaration files speed up code execution
  • Confusing declaration files with code transpilation
  • Believing declaration files create new functions
2. Which syntax correctly declares a module named 'my-lib' in a custom declaration file?
easy
A. module declare 'my-lib' { function foo(): void; }
B. declare module 'my-lib' { export function foo(): void; }
C. declare 'my-lib' module { export function foo(): void; }
D. module 'my-lib' declare { export function foo(): void; }

Solution

  1. Step 1: Recall correct module declaration syntax

    TypeScript uses declare module 'name' { ... } to declare modules.
  2. Step 2: Check each option's syntax

    Only declare module 'my-lib' { export function foo(): void; } uses the correct order and keywords.
  3. Final Answer:

    declare module 'my-lib' { export function foo(): void; } -> Option B
  4. Quick Check:

    Correct module syntax = declare module 'name' [OK]
Hint: Use 'declare module' followed by module name in quotes [OK]
Common Mistakes:
  • Swapping 'declare' and 'module' keywords
  • Omitting quotes around module name
  • Using incorrect keyword order
3. Given this declaration file snippet:
declare module 'utils' {
  export function greet(name: string): string;
}

What is the correct TypeScript output for greet('Alice') if implemented as return `Hello, ${name}!`;?
medium
A. "Hello, Alice!"
B. Error: greet is not defined
C. greet(Alice)
D. Hello, Alice!

Solution

  1. Step 1: Understand the declaration and implementation

    The declaration says greet takes a string and returns a string. The implementation returns a template string greeting.
  2. Step 2: Evaluate the output of greet('Alice')

    Calling greet('Alice') returns the string Hello, Alice! without quotes in the output.
  3. Final Answer:

    Hello, Alice! -> Option D
  4. Quick Check:

    Function returns greeting string = Hello, Alice! [OK]
Hint: String return does not include quotes in output display [OK]
Common Mistakes:
  • Including quotes around string output incorrectly
  • Confusing function call with output text
  • Assuming runtime error without implementation
4. Identify the error in this custom declaration file snippet:
declare module 'math-lib' {
  export function add(a: number, b: number): number
}
medium
A. Missing semicolon after function declaration
B. Wrong module name syntax
C. Function parameters must be optional
D. Cannot export functions in declaration files

Solution

  1. Step 1: Check syntax inside module declaration

    Each statement inside declaration files must end with a semicolon.
  2. Step 2: Identify missing semicolon

    The function declaration line lacks a semicolon at the end.
  3. Final Answer:

    Missing semicolon after function declaration -> Option A
  4. Quick Check:

    Declaration statements need semicolons [OK]
Hint: Always end declarations with semicolons [OK]
Common Mistakes:
  • Forgetting semicolons in declaration files
  • Thinking exports are not allowed
  • Misnaming modules with wrong quotes
5. You want to add a global type for a new property window.myAppVersion in a TypeScript project. Which custom declaration file snippet correctly adds this global property?
hard
A. declare module 'global' { interface Window { myAppVersion: string; } }
B. declare module 'window' { export const myAppVersion: string; }
C. declare global { interface Window { myAppVersion: string; } } export {};
D. interface Window { myAppVersion: string; }

Solution

  1. Step 1: Understand how to add global types

    Use declare global block to augment global interfaces like Window.
  2. Step 2: Check each option for correct syntax

    declare global { interface Window { myAppVersion: string; } } export {}; correctly declares global and extends Window interface, then exports empty to make it a module.
  3. Final Answer:

    declare global { interface Window { myAppVersion: string; } } export {}; -> Option C
  4. Quick Check:

    Global augmentation uses declare global + interface extension [OK]
Hint: Use 'declare global' to add global types safely [OK]
Common Mistakes:
  • Trying to declare global types inside a module
  • Omitting export {} to make file a module
  • Declaring interface without 'declare global'
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard