参数类型检查的约定是什么?我正在为我自己和其他一些人使用的小型图书馆工作。库中有许多接受大量参数的方法。我应该检查以确保这些参数是正确的类型。如果是这样,最好的方法是什么。
我目前正在为2d向量做的示例:
function Vec2 (x, y) {
// default to 0's if numbers aren't provided
// should this check for numbers differently?
// should this just fail silently?
// should this just accept whatever's given to it?
if (x.constructor !== Number) {
x = 0;
}
if (y.constructor !== Number) {
y = 0;
}
// store components
this.x = x;
this.y = y;
}
// an example method
Vec2.prototype.plus = function (vector) {
// throw a type-error if its not "Vec2"
// should this check for "Vec2"'s differently?
// should this just fail silently?
// should this use duck-typing and accept anything resembling {x : 1, y : 2}?
// should this just accept whatever's given to it?
if (vector.constructor !== Vec2) {
throw new TypeError('The provided vector is not of type "Vec2".');
}
return new Vec2(this.x + vector.x, this.y + vector.y);
};