最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript - Pass interface literals to function parameters - Stack Overflow

programmeradmin0浏览0评论

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

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
    },
});
Share Improve this question edited Aug 16, 2016 at 9:23 Radim Köhler 124k48 gold badges242 silver badges340 bronze badges asked Aug 16, 2016 at 9:15 Paul RedmondPaul Redmond 3,2964 gold badges35 silver badges53 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 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

发布评论

评论列表(0)

  1. 暂无评论