Paul Redmond Paul Redmond - 3 months ago 35
TypeScript Question

Typescript - Pass interface literals to function parameters

I want to use an interface to set the data types and then call them in the function while setting a default value if they are not passed through.

I get an error of

',' expected.
after canvas in the function. Can't I call it in this way?

// Options
interface options {
canvas?: {
width: number;
height: number;
bgColor: string;
};
brushes?: {
sizeSm: number;
sizeLg: number;
};
}

function initialize(options {canvas.width = 700, brushes.sizeSm = 20}) {
// Do stuff
}

// Call function
initialize({
canvas: {
width: 820,
height: 450,
bgColor: '#fff'
},
brushes: {
sizeSm: 10,
sizeLg: 20
},
});

Answer

This should be working

interface options {
    canvas?: {
        width: number;
        height?: number;
        bgColor?: string;
    };
    brushes?: {
        sizeSm: number;
        sizeLg?: number;
    };
}

function initialize(opts: options = {canvas : { width : 700}, brushes: {sizeSm : 20}} ) {
//function initialize(options {canvas.width = 700, brushes.sizeSm = 20}) {
    // Do stuff
}

// Call function
initialize({
    canvas: {
        width: 820,
        height: 450,
        bgColor: '#fff'
    },
    brushes: {
        sizeSm: 10,
        sizeLg: 20
    },
});

Firstly, the syntax of the options as a paramter should be adjusted to consume the interface opts: options.

Next, if we want want to have a default value, we need to properly pass it:

function initialize(opts: options = {canvas : { width : 700}, brushes: {sizeSm : 20}} ) {

And because we set only width and sizeSm .. the rest is adjusted to be optional (e.g. heigth?:number)

Play with that here