A great alternative to TypeScript is JSDOC. JSDoc is an open source API documentation generator for Javascript. You can also use typeof to check for primitive types or you can use duck typing. Duck typing is a programming style that uses the "duck test" to determine if an object can be used for a specific purpose. The test states, "If it walks like a duck and it quacks like a duck, then it must be a duck".
Here are some example Javascript functions that can help you get started with type safety.
function doThrowError(error, doThrow) {
if (doThrow === 'DO_THROW') {
console.warn(error);
return null;
} else {
throw new TypeError(error);
}
}
function confirmType(type, doThrow) {
if (type && typeof type[0] !== type[1]) {
const error = `${type[0]} must be a ${type[1]}.`;
return doThrowError(error, doThrow);
}
return true;
}
function confirmTypeString(type, doThrow) {
return confirmType([type, 'string'], doThrow);
}
function confirmTypeFunction(type, doThrow) {
return confirmType([type, 'function'], doThrow);
}
function confirmTypeNumber(type, doThrow) {
return confirmType([type, 'number'], doThrow);
}
Calvin C.
And here is how you might use one of the above functions. /** * @param {Number} num * @returns {Number} * @throws {TypeError} */ function addTwo(num) { if (confirmTypeNumber(num)) { return num + 2; } } addTwo("8"); // This will throw a TypeError addTwo(8); // 1008/19/24