Modules Scripts and Declaration Files 7 exercises
explainer

Declaration Files in TypeScript

Declaration files are where you declare the types for TypeScript. They're marked by the .d.ts extension.

Consider the can't-use-runtime-code.d.ts file, which contains a function myFunc that has an error:


// can't-use-runtime-code.d.ts
export const myFunc = () => {}; // red squiggly li

Loading explainer

Transcript

00:00 Now we're gonna talk about declaration files. Declaration files are a special type of file in TypeScript that you basically declare by using a .d.ts extension. So here we have a normal TypeScript file, index.ts, and next to it we have a can't-use-runtime-code.d.ts file.

00:18 I've named it like this because you can't use runtime code inside a .d.ts file. Declaration files are just for types. So inside here we have a myfunc declaration which basically says a const initializer in an ambient context must be a string or numeric literal or literal enum reference.

00:36 What this basically means is you can't use runtime code in a declaration file, and implementation cannot be declared in ambient contexts. So an ambient context is what TypeScript calls this sort of scope inside a declaration file. And so basically saying you can't use runtime code here. Sorry, schmuck.

00:54 But you can declare types. So declaring types is perfectly fine in a declaration file. So we've got mytype here, equals string, and we're exporting it too. So we've got export mytype equals string, export interface, myinterface. And then if we look inside index.ts, you can see that we're importing them here too and that we're expecting them to be the right type.

01:13 And of course, if we change them over, so if I go to myinterface here and declare it as myprop number, then if I go back to the other file, then this is going to be erroring because it's expecting myprop to be a string. Let me just change that back. Just so the TypeScript gods don't get angry with me. So this is a basic introduction to declaration files. You can declare types in them.

01:33 You can't declare runtime code in them. And you can export stuff from them if you want.