1

I got this typescript code:

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

function createSquare(config: SquareConfig): { color: string; area: number } 
{
    return { color: "blue", area: 1};
}

let mySquare = createSquare({ colour: "red", width: 100 });

There is a deliberate error when calling the method - the object passed is with a property called "colour" instead of "color".

I don't understand why typescript says its an error, since the "color" property of the interface is defined as an optional parameter...

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
  • 3
    `color` is indeed optional, but it has nothing to do with the fact that `colour` property isn't part of the defined interface – haim770 Jan 01 '19 at 17:43
  • E.g., it's a typo, trying to use UK-derived spelling for a property named with U.S. spelling. – T.J. Crowder Jan 01 '19 at 17:48
  • @haim770 then what does an "optional" property means here? doesn't it mean i can pass an object which doesn't have the color property? – CodeMonkey Jan 01 '19 at 17:53
  • @YonatanNir, You can. It's only the excessive property that is causing the error. `createSquare({width:100})` is perfectly fine – haim770 Jan 01 '19 at 17:57
  • 1
    The existence of the `color` property is entirely irrelevant to the error – Ryan Cavanaugh Jan 01 '19 at 17:59
  • @haim770 Then it means that if the object has a single property, it could be either one, but if it got 2 properties then it must be both of them? With the same logic, does it mean that if there's a single property then it MUST be either color or width? – CodeMonkey Jan 01 '19 at 18:12

0 Answers0