-
-
Notifications
You must be signed in to change notification settings - Fork 10
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
Improve the hasProperty
function
#79
Conversation
This comment was marked as resolved.
This comment was marked as resolved.
@@ -36,6 +36,20 @@ if (isObject(unknownObject)) { | |||
expectNotAssignable<Record<'foo', unknown>>(unknownObject); | |||
} | |||
|
|||
// An object is accepted after `hasProperty` is used to prove that it has the required property. | |||
if (isObject(unknownObject) && hasProperty(unknownObject, 'foo')) { | |||
expectAssignable<Record<'foo', unknown>>(unknownObject); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These two tests were failing before these changes
>( | ||
objectToCheck: ObjectToCheck, | ||
name: Property, | ||
): objectToCheck is ObjectToCheck & Record<Property, unknown> => |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
// [['foo'], 0], | ||
// [['foo'], '0'], | ||
] as any[] | ||
] as const |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These array test cases didn't seem relevant because they contradicted the input type.
The `hasProperty` function now tells TypeScript that the property exists, making it more effective as a type guard. A `ValidPropertyTypes` type has been added as well, for convenience.
c2670bf
to
dd1bcc4
Compare
@@ -32,10 +32,14 @@ export type PartialOrAbsent<Value> = Partial<Value> | null | undefined; | |||
export type NonEmptyArray<Element> = [Element, ...Element[]]; | |||
|
|||
/** | |||
* A JavaScript object that is not `null`, a function, or an array. The object | |||
* can still be an instance of a class. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oops, this deletion was intended to be in #78. The tests added there show that instances of a class were not compatible with the RuntimeObject
type.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is great. 👍
The
hasProperty
function now tells TypeScript that the property exists, making it more effective as a type guard.A
ValidPropertyTypes
type has been added as well, for convenience.