dev-resources.site
for different kinds of informations.
Nano "Typescript" without compilation
Published at
3/28/2024
Categories
javascript
typescript
programming
Author
Eckehard
Thanks to this post from Toby Farley (Shadow Chicken), I had an inspiration to build my own tiny little nano "typescript" running without compilation.
Ok, typescript provides much more, but if you only need some typechecks, this little routine would do the trick:
/* ==================================================
Nano typeCheck
Valid types
"var": Variant - all types allowed
"string"
"number"
"bigInt"
"boolean"
"object"
"array"
"date"
"set"
"function"
================================================== */
function typeCheck(v) {
if ((typeof v) !== "object") throw (`Parameter must be Object in function ${typeCheck.caller.name}`)
// Build return value array
let res = Object.entries(v).map((a, i) => {
let [typ, val] = a; // get key/values
typ = typ.charAt(0).toUpperCase() + typ.slice(1) // Capitalize
if (typ === "Var") // Variant type
return val
if (val.constructor.name !== typ) // check type
throw (`Type error parameter ${i + 1} is not ${typ} in function ${typeCheck.caller.name}`)
return (val)
})
return res
}
function myFunc(a,b,c,d) {
typeCheck({ string: a, boolean: b, array: c, var: d })
console.log(a)
console.log(b)
console.log(c)
console.log(d)
}
myFunc( "5", true, [1, 2, 3, 4, 5], "Do what you want")
You can also submit typ declaration with the parameters like this:
function myFunc(pars) {
let [a, b, c, d] = typeCheck(pars)
console.log(a)
console.log(b)
console.log(c)
console.log(d)
}
myFunc({ string: "5", boolean: true, array: [1, 2, 3, 4, 5], var: "Do what you want" })
Types can be named using the standard type names with lower or upper case, so both would be accepted:
{ string: a, boolean: b, array: c, var: d }
{ String: a, Boolean: b, Array: c, Var: d }
Tell me, what you think.
P.S.: This post was changed after the first sumbission to show different ways of usage.
Articles
12 articles in total
About the "S" in Solid
read article
One Byte Explainer: Homogenous coordinates
read article
Object Oriented Programming
read article
Flems.io
read article
Revisiting the "Revealing Module pattern"
read article
Measuring performance
read article
Nano "Typescript" without compilation
currently reading
6 times faster loops in Javascript
read article
Better event throttle
read article
Better array concat...
read article
Easy Math in Javascript
read article
Loops the functional way
read article
Featured ones: