Kevin Powell - CommunityKP-C
Kevin Powell - Communityβ€’4w agoβ€’
5 replies
Faker

Purpose of declare keyword in TypeScript

Hello, can someone explain the purpose of the declare keyword in typescript please. I don't understand why do we need it, what if we omit it?

I read about it in a stackoverflow forum where the declare keyword just tells the compiler that "believe that the variable of backpack" exists. I don't understand why we need to "explicitly" do that though, what would happen at runtime pls.
interface Backpack<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}
 
// This line is a shortcut to tell TypeScript there is a
// constant called `backpack`, and to not worry about where it came from.
declare const backpack: Backpack<string>;
 
// object is a string, because we declared it above as the variable part of Backpack.
const object = backpack.get();
 
// Since the backpack variable is a string, you can't pass a number to the add function.
backpack.add(23);
Argument of type 'number' is not assignable to parameter of type 'string'.
Was this page helpful?