Reputation: 26160
There is a snipet with no error in return of funciton with decared return type.
type Human = {
head: number
body: number
}
const human: Human = {
head: 1,
body: 1,
}
const humanFn: (human: Human) => Human = (human) => {
return {
// ...human,
head: human.head,
body: human.body,
tail: 1, // allows illegal props
}
}
humanFn({
...human,
tail: 1, // here is and error
})
So the question is why TS allows adding additinal props to return object tail: 1, // allows illegal props
? Is there a way to avoid it?
UPD:
so actually I found the exiting TS issue https://github.com/microsoft/TypeScript/issues/241
And "workaround" to wrap return object in something like R.identity<Human>(...)
(from ramda)
Upvotes: 1
Views: 1117
Reputation: 15562
Your code does not throw a compile error,
but the following code throws a compile error.
function humanFn(human: Human): Human {
return {
// ...human,
head: human.head,
body: human.body,
tail: 1, // Error
}
}
and the following also does throw a compile error
const humanFn: (human: Human) => Human = (human): Human => {
return {
// ...human,
head: human.head,
body: human.body,
tail: 1, // Error
}
}
Your question seems to be another case of this question.
Finally I found the issue in GitHub, exactly about the problem. In short:
Ideally this would be an error. Unfortunately it turns out to be very difficult to fix this without possibly having consequences in terms of runaway recursion and/or performance
Upvotes: 3