When defining a function's return type we'll receive a type error if we include a property in the returned object that is not present in the return type, stating 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', // Problem
}
}
When defining a function type, we'll receive a type error when omitting a known property from the returned object, stating that the known 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',
}
}
However, again when defining a function type–which correctly raises a type error for missing properties–a type error will not be raised when returning an object containing extra properties:
const foo: () => {status: string} = function () {
return {
status: '200 OK',
bar: 'baz', // No problem
}
}
- Why does the final example not raise a type error?
- Is there any way to enforce "no extra properties" on the return object using a function type?
See in playground
question from:
https://stackoverflow.com/questions/65642323/can-no-unknown-properties-be-enforced-using-function-types 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…