打字稿声明参考引发错误

发布于 2025-02-06 03:09:44 字数 741 浏览 2 评论 0原文

我想了解nectare关键字背后的概念,并且我尝试运行可重复使用的类型(接口)示例:

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

declare function greet(setting: GreetingSettings): void;

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

但是我遇到了一个错误:entry未定义

TypeScript Playground Link

Is this the expected behavior of the declare keyword ?如果是,我该怎么办,我不会遇到此错误?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

二智少女 2025-02-13 03:09:44

这是声明关键字的预期行为吗?

是的。 声明的目的是告诉Typescript某些东西已经存在以及其形状是什么。例如,在浏览器环境中有一个声明 for settimeout,以告诉Typescript浏览器提供该功能。 声明在运行时没有创建任何内容,这纯粹是将输入类型的类型信息与其他地方创建的内容相关联。 (我想说这不是很惊人的记录[或者我找不到],但是部分涵盖了在这里以及手册的其他地方。

-files / 存在,因此将其调用会给您带来运行时错误。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文