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

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

一、他是的使用与支持

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

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

二、示例展示

简要示例代码如下:

复制代码
// @ts-check

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

x="12";
复制代码

效果图如下:

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

三、疑问

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
posted @   小龙女先生  阅读(3034)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示