When dealing with two overloads of update
, I can differentiate between them by inspecting the first parameter:
class CRC16 {
update(buffer: number[], offset: number, length: number): number;
update(data: number): number;
update(buffer: number[] | number, offset?: number, length?: number) {
if (Array.isArray(buffer) // Checking first parameter
&& offset !== undefined && length !== undefined) // These checks may be unnecessary
return length - offset;
else
return 1;
}
}
const c = new CRC16();
console.log(
c.update(1),
c.update([1, 2, 3, 4], 1, 4));
Dealing with
error TS2532: Object is possibly 'undefined'
issues related to length
and offset</code when I remove the redundant checks from the code. (Even though typescript already disallows calling <code>c.update([1, 2, 3, 4])
due to it not matching any overload.) Is there a more succinct way to handle this without meticulously examining every parameter?