将js文件加载到打字稿文件中

编程入门 行业动态 更新时间:2024-10-27 10:32:25
本文介绍了将js文件加载到打字稿文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个简单的 TypeScript (ts),它需要一个来自 JavaScript 文件的函数.如何将该js文件导入ts文件?我是否必须为该 js 文件创建一个 ts 文件才能在我的 ts 文件中使用它?

I have a simple TypeScript (ts) which needs a function from a JavaScript file. How can I import that js file into ts file? Do I have to create a ts file for that js file to be able to use it in my ts file?

推荐答案

最简单的方法就是声明你正在使用的函数:

The easiest way is to just declare the function you're using:

File1.js

function greet() { return "Hello!"; }

File2.ts

declare function greet(): string;

/* ... later ... */
var hi = greet();

<小时>

如果您的场景更复杂(即多个文件引用 File1.js,或者 File1.js 中有许多函数会混淆 File2.ts),您可以创建一个 File1.d.ts 文件并从File2.ts:


If your scenario is more complex (i.e. multiple files referencing File1.js, or there are many functions in File1.js that would clutter up File2.ts), you can make a File1.d.ts file and reference that from File2.ts:

File1.d.ts

function greet(): string;

File2.ts

/// <reference path="File1.d.ts" />

/* ... later ... */
var hi = greet();

这篇关于将js文件加载到打字稿文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-29 10:03:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1187574.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   加载   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!