[求教]利用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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM