如何在typescript中使用接口可选属性

时间:2018-04-23 18:03:58

标签: typescript interface

我正在阅读有关TypeScript的文档并遇到此问题:

interface SquareConfig {
    color?: string;
    width?: number;
}

function createSquare(config: SquareConfig): { color: string; area: number } {
    let newSquare = {color: "white", area: 100};
    if (config.clor) {
        // Error: Property 'clor' does not exist on type 'SquareConfig'
        newSquare.color = config.clor;
    }
    if (config.width) {
        newSquare.area = config.width * config.width;
    }
    return newSquare;
}

let mySquare = createSquare({color: "black"});

我不明白为什么有{color:string; area:number}在createSquare之后(config:SquareConfig): 有人可以解释一下吗?

1 个答案:

答案 0 :(得分:4)

函数参数后面的“:”表示返回类型。此函数返回一个具有“color”和“string”属性的对象。