4

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
    },
});
0

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Wow, this looks like what I'm after. Of course, I have to set the parameter to the interface. One thing, I've done as above and I'm getting Identifier expected for the values, e.g. {width : 700}.
because you've used this function initialize(options {canvas : { width : 700}... and this is wrong.. because we miss the interface as a type. we need that (as in my answer) function initialize(opts: options = {canvas : { width : 700}. the opts is variable name, the :options is type and after = we can see the default value.. hope that helps a bit ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.