Kagami Sascha Rosylight
Kagami Sascha Rosylight

Reputation: 1492

Can a function have `multiple optional parameters' that is simultaneously required?

I'm currently trying to polyfill createImageBitmap function.

[NoInterfaceObject, Exposed=Window,Worker]
interface ImageBitmapFactories {
  Promise createImageBitmap(ImageBitmapSource image, optional long sx, long sy, long sw, long sh);
};

It seems that this function allows createImageBitmap(image) and createImageBitmap(image, sx, sy, sw, sh) but not else, for example, createImageBitmap(image, 0, 0).

How can I do this in TypeScript? I cannot do this by:

function createImageBitmap(image: any, sx?: number, sy: number, width: number, height: number) { }

... as this fails to compile.

Upvotes: 1

Views: 1350

Answers (2)

Acidic
Acidic

Reputation: 6280

Looks like you need function overloading:

function createImageBitmap(image: any);
function createImageBitmap(image: any, sx: number, sy: number, width: number, height: number);
function createImageBitmap(image: any, sx?: number, sy?: number, width?: number, height?: number) {
    // ...
}

Upvotes: 1

basarat
basarat

Reputation: 276293

You would need function overloading:

declare function createImageBitmap(image: any, sx: number, sy: number, width: number, height: number);
declare function createImageBitmap(image: any, sy: number, width: number, height: number);

But I think you have the declaration wrong. all x,y,w,h are optional:

enter image description here

Upvotes: 2

Related Questions