在 TypeScript 中使用 declare 关键字

Muhammad Ibrahim Alvi 2023年10月12日
在 TypeScript 中使用 declare 关键字

本文解释了 TypeScript 中 declare 关键字的用途,其中包含在开发人员社区中完成的真实编码示例和实现。它还将为读者提供在 TypeScript 中使用 declare 关键字的优势。

让我们深入了解本教程并开始学习。

在 TypeScript 中使用 declare 关键字

TypeScript declare 关键字用于方法或变量的环境声明。环境声明也可以被认为是一个导入关键字,通知编译器源存在于另一个文件中。

我们主要使用 TypeScript 中的 Ambient 声明来使用 NodejQueryJavaScript 等第三方库。直接使用 declare 关键字将这些库集成到我们的代码中将减少我们的错误机会 TypeScript 代码。

以下是用于 declare 关键字的语法。

declare var variableName;
declare module nameOfModule{// Body of module
};

让我们考虑以下代码示例,其中我们有第三方 JavaScript 代码,其中包含一些变量的值,但我们不需要更改它们;相反,我们想用它来使用 declare 关键字来达到这个目的。

例如,我们有一个包含一些有用变量的文件,但该文件是用 JavaScript 编写的。由于我们想在 TypeScript 中使用它而不重写代码,因为它很耗时,我们可以使用 declare 关键字。

参考下面的第三方代码。

// JavaScript Code
var pi_one = 3.1415926535;
var pi_two = 3.14159265358979323846;
var pi_three = 3.141592653589793238462643383279;
//TypeScript Code
declare var pi_one : any ;

console.log("Value of pi is :",pi_one)

现在我们可以将文件与 HTML 代码链接并使用它们。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>declare keyword</title>
</head>
<body>

</body>
       <!-- Javascript Library -->
    <script src="C:\Users\computers\Desktop\typescript\first1.js">
    </script>
    <script src="C:\Users\computers\Desktop\typescript\secons.js">
    </script>
</html>

上面代码的输出将在下面。

在 TypeScript 中使用 declare 关键字

Muhammad Ibrahim Alvi avatar Muhammad Ibrahim Alvi avatar

Ibrahim is a Full Stack developer working as a Software Engineer in a reputable international organization. He has work experience in technologies stack like MERN and Spring Boot. He is an enthusiastic JavaScript lover who loves to provide and share research-based solutions to problems. He loves problem-solving and loves to write solutions of those problems with implemented solutions.

LinkedIn