Issue
** Code 1: **
interface Point {
x: number;
y: number;
}
function logPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
// logs "12, 26"
const point = { x: 12, y: 26, z:"newfield" };
logPoint(point);
**Code 2: **
interface SquareConfig {
color?: string;
width?: number;
}
function createSquare(config: SquareConfig) {
return {
color: config.color || "red",
area: config.width ? config.width \* config.width : 20,
};
}
let mySquare = createSquare({ color: "red", width: 100 , z:"newfield"});
I'm getting the following error in the code 2 but not in code 1.
Object literal may only specify known properties, and 'z' does not exist in type 'SquareConfig'.
Can someone please explain this behavior to me?
I was expecting why this is behaving differently.
Edit :
I noticed this strange behavior In code 2 If we call createSquare following way Error disappeared
const val = { color: "red", width: 100, z:"newfield"}
let mySquare = createSquare(val);
Solution
The reason is because you have not defined z
in your SquareConfig
type, therefore adding z
is considered "not allowed" by the compiler.
If you added z
to the SquareConfig
the compiler would not throw this error at you
interface SquareConfig {
color?: string;
width?: number;
z?: string
}
function createSquare(config: SquareConfig) {
return {
color: config.color || "red",
area: config.width ? config.width: 20,
};
}
let mySquare = createSquare({ color: "red", width: 100 , z:"newfield"});
Edit:
The compiler is reading your SquareConfig
and then sees you call createSquare
, and says, "well you can't do that because z
wasn't defined in that type so you can't add it in now"
Conversely, if you didn't define z
, but then you were trying to access it inside createSquare
, then the compiler would say pretty much the same, "you can't access this z
property because I don't know what that is since it doesn't exist in SquareConfig
"
These are not verbatim messages.
Edit to address code 1
In code 1, the compiler is being a bit more relaxed with you because z
is being defined in const point
, but that is an Object but hasn't been defined as Point
.
This throws an error because Point
cannot have z
.
const point:Point = { x: 12, y: 26, z:"newfield" };
However the compiler lets you get away with it here because the the object point
contains all the keys necessary for logPoint
function logPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
// logs "12, 26"
const point = { x: 12, y: 26, z:"newfield" };
logPoint(point);
Answered By - Harrison
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.