I have two overloads of update. I can determine which overload I'm in by examining 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) // Examine first parameter
&& offset !== undefined && length !== undefined) // These checks are redundant
return length - offset;
else
return 1;
}
}
const c = new CRC16();
console.log(
c.update(1),
c.update([1, 2, 3, 4], 1, 4));
Typescript gives error TS2532: Object is possibly 'undefined' errors for length and offset if I comment out the redundant checks on the remaining parameters. (The redundant checks protect against an invocation like c.update([1, 2, 3, 4]), but typescript prohibits that anyways because it's not in any overload.) Is there a way to write this so I don't have to ceremoniously examine every parameter?