TSConfig文件详解26

编译器配置项-compilerOptions

JavaScript支持配置项01

使用JavaScirpt-allowJs

允许在项目中导入 JavaScript 文件,而不仅仅是 .ts.tsx 文件。例如这个.js文件:

// @filename: card.js
export const defaultCardDeck = "Heart";

当一个TypeScript文件导入它时将报错:

// @filename: index.ts
import { defaultCardDeck } from "./card";

console.log(defaultCardDeck);

如果allowJs被启用:

// @filename: index.ts
import { defaultCardDeck } from "./card";

console.log(defaultCardDeck);

这个选型可以用来在JavaScript的项目中增量添加TypeScript文件,从而使.ts/.tsx文件

与现有 JavaScript 文件一起存在。

该选项还可以和 declaration / emitDeclarationOnly 一起工作 为JS文件生成声明文件

检查JS文件 - checkJs

allowJs 协同工作。启用该选项后,等效于工程中的JavaScript文件顶部添加//@ts-check注释。

例如,根据TypeScript对parseFloat的类型声明,下边的JavaScript代码是不正确的:

// parseFloat only takes a string
module.exports.pi = parseFloat(3.142);

当被TypeScript文件导入时:

// @filename: constants.js
module.exports.pi = parseFloat(3.142);

// @filename: index.ts
import { pi } from "./constants";
console.log(pi);

未启用checkJs 之前不会收到任何错误,但是,启用 checkJs之后,JavaScript 文件将收到错误消息Argument of type 'number' is not assignable to parameter of type 'string'.

// @filename: constants.js
module.exports.pi = parseFloat(3.142);
// Argument of type 'number' is not assignable to parameter of type 'string'.

// @filename: index.ts
import { pi } from "./constants";
console.log(pi);

Js模块依赖最大深度 - maxNodeModuleJsDepth

node_modules 目录中索并加载 JavaScript 文件的最大依赖深度。

该标志只能在启用了 allowJs 时使用,并且如果您想让TypeScript为node_modules 内的所有提供JavaScript推断类型,则可以启用该选项。

理想情况下,该值应保持默认值0,并且应使用 .d.ts 文件来显式定义引用模块的类型。但是,在某些情况下,您可能希望以牺牲速度和潜在准确性为代价来启用此功能。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容