Home > Net >  TypeScript declare reference throws error
TypeScript declare reference throws error

Time:06-10

I want to understand the concept behind the declare keyword in practice, and I have tried to run Reusable Types (Interfaces) example:

interface GreetingSettings {
  greeting: string;
  duration?: number;
  color?: string;
}

declare function greet(setting: GreetingSettings): void;

greet({
  greeting: "hello world",
  duration: 4000
});

But I get an error: greet is not defined

TypeScript Playground Link

Is this the expected behavior of the declare keyword? If yes, what should I do that I would not get this error?

CodePudding user response:

Is this the expected behavior of the declare keyword?

Yes. The purpose of declare is to tell TypeScript that something already exists and what its shape is. For example, there's a declare for setTimeout in the browser environment to tell TypeScript that the browser provides that function. declare doesn't create anything at runtime, it's purely to associate type information for TypeScript with something created elsewhere. (I'd say this isn't astonishingly-well documented [or I just can't find it], but it is covered in part here and elsewhere in the part of the handbook.)

In your case, it would appear that greet does not already exist, so calling it gives you a runtime error.

  • Related