TypeScript Run time Type Checking Supplement Tool

  • 2021-08-28 19:10:14
  • OfStack

TypeScript is a static type system that does type checking at compile time. 1 In general, if all the libraries and modules used in the project are based on ts, static typing can already avoid most of the programming level typing problems. However, in some scenarios, static types alone cannot solve the problem, and some data are dynamically passed into the system, mainly including the following scenarios:

Third-party data sources (interface API, local persistent storage, postMessage, etc.) Third-party caller pass parameter Global state change

Of course, there are other possibilities. In short, static type checking alone cannot solve the runtime type problem. Therefore, I wrote the tool tyshemo. It can help us complete the type check at runtime. It exposes many interfaces, among which Ty interface is very suitable for js as a supplement to ts. Let's take a look.


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

We can use Ty. decorate. with () as a decorator to qualify the value types of properties, method parameters, and return value types on a class.

In normal programs, we sometimes need to limit the value, but because of the characteristics of js language, we can't listen to the value of the basic type, but we can listen to object. We can do the following:


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

To control the current environment through process.env.NODE_ENV = = = 'production', this ability is not needed in the formal environment, after all, we have fully verified it in the test environment.

To check the data from API, we can do this.


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 is an interface that allows you to quickly structure your data. tyshemo has many other capabilities, and you can learn more about them in its documentation.


Related articles: