When specifying the return type of a function, including a property in the returned object that is not part of the return type will result in a type error, indicating that object literals may only specify known properties.
// Type '{ status: string; bar: string; }' is not assignable to type '{ status: string; }'.
// Object literal may only specify known properties, and 'bar' does not exist in type '{ status: string; }'.(2322)
const foo = function(): {status: string} {
return {
status: '200 OK',
bar: 'baz', // Issue
}
}
When defining a function type, failing to include a defined property within the returned object will trigger a type error, signaling that the specified property is missing:
// Type '() => { baz: string; }' is not assignable to type '() => { status: string; }'.
// Property 'status' is missing in type '{ bar: string; }' but required in type '{ status: string; }'.(2322)
const foo: () => {status: string} = function () {
return {
// status: '200 OK'
bar: 'baz',
}
}
Interestingly, in this context of setting a function type where missing properties are detected, returning an object with additional properties does not lead to a type error:
const foo: () => {status: string} = function () {
return {
status: '200 OK',
bar: 'baz', // No issue
}
}
- Why doesn't the final example generate a type error?
- Is there a way to enforce "no extra properties" on the return object using a function type?