TypeScript是靜態類型系統,在編譯時作類型檢查。通常而言,若是項目所用到的全部庫、模塊都是基於ts的,那麼靜態類型已經能夠避免大部分編程層面的類型問題。不過,在一些場景下來,單純靜態類型是沒法解決問題的,部分數據是動態傳入到系統中的,主要包含場景以下:git
固然,還有其餘可能,總之,單純靠靜態類型檢查,沒法解決運行時類型問題。所以,我寫了tyshemo這個工具。它能夠幫助咱們完成運行時的類型檢查。它暴露了不少接口,其中的Ty接口,很適合在js中做爲ts的補充被使用,咱們來看下。github
import { Ty } from 'tyshemo' @Ty.decorate.with([Number, Number]) class Some { constructor(a, b) { this.x = a + b } @Ty.decorate.with(String) name = 'calc' @Ty.decorate.with([Number], Number) plus(y) { return this.x + y } } const some = new Some(1, 3) // ok const some2 = new Some('1', '3') // throw error some.name = 'ooo' // ok some.name = 123 // throw error const z = some.plus(2) // ok const z1 = some.plus('3') // throw error
咱們能夠經過 Ty.decorate.with()
做爲裝飾器來限定一個類上屬性的值類型,方法的參數和返回值類型。編程
在正常的程序中,咱們有的時候也須要對值進行限定,可是因爲js語言的特性,咱們沒法對基礎類型的值進行監聽,不過咱們能夠對object進行監聽。咱們能夠以下操做:工具
const o = process.env.NODE_ENV === 'production' ? {} : Ty.decorate({}).with({ name: String, age: Number, }) o.name = null // throw error o.name = 'aaa' // ok o.age = '12' // throw error o.age = 12 // ok
經過 process.env.NODE_ENV === 'production'
來控制當前環境,若是在正式環境,就不須要這個能力,畢竟咱們在測試環境已經作過充分驗證了。post
要對來自API的數據進行檢查,咱們能夠這樣操做。測試
function getData(url) { return fetch(url).then(res => res()).then((data) => { if (process.env.NODE_ENV !== 'production') { Ty.expect(data).to.be({ name: String, age: Number, }) } return data }) }
Ty
這個接口能夠快速對數據進行結構化檢查。tyshemo還有不少其餘方面的能力,能夠在它的文檔中瞭解更多。fetch