-
Notifications
You must be signed in to change notification settings - Fork 12.6k
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
Incorrect type inference when get/set accessors use different types #51229
Comments
I believe this is working as intended. Object literals don't use the setter method, so whatever logic may cause the value to transform is not running. When you try to get this property the type will still wrongly be The assignment works using at type assertion ( |
Also, even your first example (that you claim works) is wrong: const foo = {} as Foo;
const bar = foo.bar; // typeof bar is Date
foo.bar = 123; // can be set by number
console.log(foo.bar); // prints a number, not a date! The only correct way to implement the interface |
I'd also like to point out an unsoundness regarding such getter/setter: Even when you assign a valid object literal, you may end up with unsound behavior when assigning a value to the property. interface Foo {
get bar(): Date;
set bar(value: Date | number);
}
const f: Foo = { bar: new Date() }
f.bar = 1;
console.log(typeof f.bar) // number |
I just use interface Foo as an example. I'm just writing *.d.ts for a JavaScript library and some properties works like this. |
It works if the property is implemented accordingly (getter/setter). Your object literal doesn't do this. |
I understand. That library is using a function that copies attributes of the literal object to another object through |
The properties of an old library allows setting many types, but only getting one type. This is represented by Date.
When this object is get or set individually, it will work properly.
However, when I set this object literally, it will not work properly.
Some properties are allowed to be set in many types, but can only be get in one type, which is more convenient.
ref #2521
The text was updated successfully, but these errors were encountered: