[求教]利用typescript对Javascript做强类型检测提示

时间:2021-06-10 16:06:59

近期在学习typescript的时候,发现ts居然可以对原生js做强检测。发现从v2.3就开始直接了。这让我感叹他的变化,又让我自己感到学习的缓慢。本文章就对他小试牛刀一下。

一、他是的使用与支持

通过阅读官网的说明,了解到他实现验证是通过jsdoc的注释结构实现。然后在.js文件头部加入如下注释标签即可:

标记 说明
// @ts-nocheck 标记此文件不做类型检测
// @ts-check 标记此文件做类型检测,但没有用--checkJS参数时
// @ts-ignore 标记后面一段不做类型检测(可以说是后面一行)

二、示例展示

简要示例代码如下:

// @ts-check

/**
* @type {number}
*/
var x;

x
="12";

效果图如下:

[求教]利用typescript对Javascript做强类型检测提示

是否很神奇,编译环境能识别出类型的差异。其他测试截图如下:

[求教]利用typescript对Javascript做强类型检测提示

三、疑问

1. 按照官网的说明,对object对象也可以做到检测,但测试貌似不可以,还望各位帮忙解疑(官网原话如下):

Object literals are open-ended

By default object literals in variable declarations provide the type of a declaration. No new members can be added that were not specified in the original initialization. This rule is relaxed in a .js file; object literals have an open-ended type, allowing adding and looking up properties that were not defined originally. For instance:

var obj = { a: 1 };
obj.b
= 2; // Allowed

Object literals get a default index signature [x:string]: any that allows them to be treated as open maps instead of closed objects.

Similar to other special JS checking behaviors, this behavior can be changed by specifying a JSDoc type for the variable. For example:

/** @type  */
var obj = { a: 1 };
obj.b
= 2; // Error, type {a: number} does not have property b