Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65641777/do-i-have-to-verify-every-parameter-in-a-typescript-overload

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...