El Yosemite
El Yosemite

Reputation: 103

How to work interface optional properties in typescript

I was reading the documentation about TypeScript and encounter this:

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

I didn't understand why there's { color: string; area: number } after createSquare(config: SquareConfig): Could someone explain me?

Upvotes: 0

Views: 237

Answers (1)

DaveG
DaveG

Reputation: 455

The ":" after the function parameters indicates the return type. This function returns an object with properties "color" and "string".

Upvotes: 4

Related Questions