Understanding the basic workings of TypeScript, it's clear that TypeScript transpiles code to JavaScript without adding extra behavior like type checking during execution. For instance,
function example(parameter: string): void {
console.log(parameter.charAt(1));
}
will be transpiled to:
"use strict";
function example(parameter) {
console.log(parameter.charAt(1));
}
If a JavaScript user calls example(3)
, an error
Uncaught TypeError: parameter.charAt is not a function
will be thrown.
Why am I asking this question? Because I'm planning to spend a lot of time improving my library (@yamato-daiwa/es-extensions) and significantly increasing its size. Let's look at the addElementsToArray function from version 1.6.x:
export default function addElementsToArray<ArrayElement>(
namedParameters:
{
targetArray: Array<ArrayElement>;
newElements: Array<ArrayElement>;
mutably: boolean;
} &
(
{ toStart: true; } |
{ toEnd: true; } |
{ toPosition__numerationFrom0: number; } |
{ toPosition__numerationFrom1: number; }
)
): Array<ArrayElement> {
const workpiece: Array<ArrayElement> = namedParameters.mutably ?
namedParameters.targetArray : [ ...namedParameters.targetArray ];
// more functionality...
}
With added type checking, the function now looks like this:
// import statements...
export default function addElementsToArray<ArrayElement>(
namedParameters:
Readonly<
(
{
mutably: true;
targetArray: Array<ArrayElement>;
} |
{
mutably: false;
targetArray: ReadonlyArray<ArrayElement>;
}
) &
{
newElements: ReadonlyArray<ArrayElement>;
toStart?: true;
toEnd?: true;
toPosition__numerationFrom0?: number;
toPosition__numerationFrom1?: number;
}
>
): Array<ArrayElement> {
// validation process...
// more functionality...
}
The validations have increased the function size and dependencies, making the distributable heavier. This can be crucial for front-end applications where every kilobyte matters.
In addition to these checks, we could:
- Determine which alternatively required parameters were passed when multiple were specified.
- Separate the checks for parameter types and presence.
- Log errors for incorrect subtypes of certain parameters.
Potential Issues
Non-TypeScript users may encounter bugs due to invalid parameter types, causing wasted time on investigations. Getting senior web developers' opinions on whether the increase in library size due to parameter validation is justified is important to me.
Bounty Update
This question has been answered, but I seek advice on whether increasing library size for parameter validation is acceptable or should be avoided to maintain a slim library. Input from experienced developers is appreciated.