-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Empty interface allow any object? #14606
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
In general, subtyping permits an object to have additional properties in an assignment. However, in the specific case of an object literal source object and a non-empty target type, TypeScript disallows excess properties in the object literal as an added safeguard. See #3823 for the rationale. The excess property check is not performed when the target is an empty object type since it is rarely the intent to only allow empty objects in that case. |
Actually this is quite inconsistent
gives
results in
No.1 is kinda expected
since A is object type Bug, quirk or feature? |
"Type '1' is not assignable to type 'A'." is the completely wrong error. Assignability is not used to check the |
What is my concern |
Right but that is what an explicit type annotation on an initialized binding does, it blocks type inference, overriding the inferred type with that of the annotation. Out of curiosity, why are you placing a type annotation on a binding that has an initializer? TypeScript's type inference is amazing, take advantage of it. // works perfectly and is 100% well typed
const a = {a: 3};
console.log(a.a); |
@aluanhaddad |
Well you would get a type error at the use site if there was a misspelled property but, that aside, a well specified interface is certainly valuable, in which case you'll need to declare all the properties it holds and then will be no type errors. So I'm not sure I understand how you would want the current behavior to be different. |
I posted question on SO but haven't received definite answer so I assume this might be a bug.
Why empty interface doesn't require object to be empty?
is valid code and will output
{ a: 1 }
.I would assume that adding optional property should work fine, but
ends with error
Type '{ a: number; }' is not assignable to type 'B'
.a
is not defined in interface.Non empty interface defines both what object can and must have.
Empty interface behaves like
any
.Is there explanation why empty interface behaves like this? Is this intentional or it's just a bug?
Expected behavior:
Actual behavior:
The text was updated successfully, but these errors were encountered: