TypeScript-可以禁用类型检查吗? [英] TypeScript - possible to disable type checking?

查看:1243
本文介绍了TypeScript-可以禁用类型检查吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用TypeScript时是否可以禁用类型检查?我喜欢TypeScript的类,接口等功能,但是对于我通常从事的较小的一个人项目,我真的不需要类型检查,而对于不太常见的库或最新版本的它,找不到现成的类型定义是很痛苦的事情.疼痛.谢谢

Is it possible to disable type checking when using TypeScript? I love TypeScript for classes, interface etc yet for the smaller one person projects I am normally engaged in I really don't need type checking and the pain of not finding ready made type definitions for less common libraries or the latest version of it is a pain. Thanks

推荐答案

在TypeScript中,以这种方式定义类型可能是可选的.

In TypeScript, types may be optional when defined that way.

由于您似乎最大的麻烦就是查找外部库的类型定义,因此您可以为不需要键入检查的任何变量创建环境定义:

Since it seems like the biggest pain you are having is finding type definitions for external libraries, you can create an ambient definition for any variable you don't want to type checking for:

declare var variableName: any;

例如,对于jQuery,它是 declare var $:any; .然后,您可以执行以下操作: $(#test").myNonExistentFunction(); (如果需要).

For example, for jQuery it would be declare var $: any;. Then you could do: $("#test").myNonExistentFunction(); if you wanted.

或者,在使用es2015模块时,可以执行以下代码来允许导入库:

Alternatively, when using es2015 modules the following code could be done to allow the library to be imported:

declare module "jquery" {
    var _temp: any;
    export = _temp;
}

速记环境模块声明(TS 2.0 +)

在TS 2.0+中,一种更好的禁用导入类型检查的方法是在项目中创建一个 .d.ts 文件并定义速记环境模块声明:

In TS 2.0+, a better way to disable type checking for imports is to create a .d.ts file in your project and define shorthand ambient module declarations:

declare module "jquery";
// or use a wildcard
declare module "express-*"; // or use "*" to allow everything

这将使您可以自由使用这些导入而无需进行类型检查:

This will allow you to use those imports freely without type checking:

import $ from "jquery";

$.something(); // ok at compile time, but will be an error at runtime

也就是说,这种情况下的最佳路径是项目中的 .d.ts 文件,以便根据所使用的内容逐渐定义所依赖的库的接口.

That said, the best path to take in this scenario is in a .d.ts file in your project to gradually define the interface of the library you're depending on based on what you use.

ts忽略注释(TS 2.6 +)

可以使用TypeScript 2.6+中的//@ ts-ignore 注释来禁用任何TypeScript错误.例如:

It's possible to disable any TypeScript error by using // @ts-ignore comments in TypeScript 2.6+. For example:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

尽管未经过良好测试,但这可能会导致在使用编译器时出现意外行为.除非绝对必要,否则我建议您不要使用这种方法.

That might lead to unexpected behaviour when using the compiler though because it's not well tested. I'd recommend against this approach unless absolutely necessary.

使用Babel进行转换

如果不需要类型检查,另一种选择是使用 Babel .它支持TypeScript的语法(请参见此处).

If you don't need type checking, another option is to use Babel. It supports TypeScript's syntax (see here).

这篇关于TypeScript-可以禁用类型检查吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆