typescript
/

TypeScript Declaration Files

Last Sync: Today

On this page

10
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

typescript

TypeScript Declaration Files

What are Declaration Files?

Declaration files (.d.ts) provide type information about JavaScript code without including actual implementation.

Why Use Declaration Files?

  • Provide type safety for JS libraries
  • Enable IntelliSense support
  • Improve developer experience
  • Avoid runtime errors

Basic Example

TypeScriptRead-only
1
declare function greet(name: string): void;

Module Declaration

TypeScriptRead-only
1
declare module 'my-lib' {
  export function add(a: number, b: number): number;
}

Global Declaration

TypeScriptRead-only
1
declare var version: string;

Using @types

BASHRead-only
1
npm install @types/lodash

When to Use

  • Using JavaScript libraries
  • Creating reusable libraries
  • Defining global variables
  • Adding types to existing JS code

Best Practices

  • Keep declarations accurate
  • Use existing @types packages when available
  • Avoid unnecessary declarations
  • Organize .d.ts files properly

Common Mistakes

  • Incorrect type definitions
  • Not installing @types packages
  • Mixing implementation with declaration
  • Ignoring module declarations

Conclusion

Declaration files enhance TypeScript development by providing type information for JavaScript code and external libraries.

Try it yourself

declare function greet(name: string): void;

Test Your Knowledge

Q1
of 3

.d.ts file used for?

A
Styling
B
Types
C
Routing
D
API
Q2
of 3

declare keyword?

A
Define logic
B
Define types
C
Call function
D
Create class
Q3
of 3

@types used for?

A
CSS
B
Type definitions
C
API
D
Database

Frequently Asked Questions

What is .d.ts?

Type declaration file.

Why use it?

To add types for JS code.

What is @types?

Community type definitions.

Previous

ts namespaces

Next

ts dom

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.