Do I have to verify every parameter in a typescript overload?

Viewed 51

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?

1 Answers

I think all these 3 overloads are very similar and doesn't help much. Also, why would you rename a function parameter from buffer to data? If it is different, then there should be 2 functions.

Isn't this interface enough?

update(buffer: number[] | number, offset?: number, length?: number): number

This one captures all overloads above. Then, regarding skipping the checks in your code, I don't understand the point. TypeScript provides types to your code but it doesn't prevent you from checking your function inputs, as you would with plain js.

I think you are trying to put too many "responsabilities" on the TS side.

Related