-
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
Bad types of hasOwnProperty
#20363
Comments
You can use global augmentation to do something like declare global {
interface Object {
hasOwnProperty<K extends string>(v: K): this is Record<K, any>;
}
} where you can replace the And then it would work like: function doStuff(x: object) {
if (x.hasOwnProperty('b')) {
x.b = 1; // okay
if (x.hasOwnProperty('c')) {
x.c = x.b; // okay
}
}
} which mostly gives you what you want, unless I'm missing something. |
@jcalz the thing is that I am not able to type the function so that it works. See the function If I call function hasProp('wtf', object); it works as expected and I can assign the prop to the variable: const val2 = object.wtf; If I call the function with prop as string variable instead of string though: hasProp(prop, object) I cannot assign the prop to the variable because typescript shows some error const val = object[prop]; As for me, the 2 examples are the same, but typescript understands only the with first one (extracted the code from my previous example to highlight the interesting lines). |
So your problem is you want to narrow both the object and the key with a single type guard. (Narrowing the key is probably not going to happen in the standard library, but you can do it in your own module with global augmentation.) And that isn't currently possible. There's no good way right now to manipulate type predicates like I'm not sure if this issue is a duplicate of #12798 or #10734 with a little of #12892 thrown in, or if I've misunderstood. |
Hi.
hasOwnProperty
has following type:which is not that useful for type system.
I wanted to write more useful version, but it seems to be impossible to type. So far best I could come up with is:
type
u.AnyType
mentioned above is defined like so:purpose of it is that I can work safely with values for which type is not known (as
any
allows me to do whtatever I want without checking anything).The text was updated successfully, but these errors were encountered: