In #22 we added objectHasOwn
. It's a type guard with return type to be object is (ObjectType & Record<Key, unknown>)
microsoft/TypeScript#21732 suggested a similar type guard inOperator
which has exactly the same return type of objectHasOwn
. However, inOperator
can assert property existence in prototypes while objectHasOwn
can not.
I propose a new function objectHas
here, which should have the same implementation as inOperator
. The naming changed to objectHas
to align with objectHasOwn
.
export function objectHas<ObjectType, Key extends PropertyKey>(
object: ObjectType,
key: Key,
): object is (ObjectType & Record<Key, unknown>) {
return key in object;
}
objectHasOwn
and objectHas
?See https://tc39.es/ecma262/multipage/abstract-operations.html#sec-hasproperty and https://tc39.es/ecma262/multipage/abstract-operations.html#sec-hasownproperty
#47 proposing a new function keyIn
that has the exact same function body but a different type definition and return type guard. They result in different type predicates. See microsoft/TypeScript#43284 (comment)
keyIn
, native in operator and objectHas
in
operatorNative in
operator is good at narrowing in union types. For example, #30 can be resolved by just using the in
operator.
const a: PromiseSettledResult<string> = { reason: '1', status: "rejected" }
if ('reason' in a) {
// a is now PromiseRejectedResult
}
(But be careful that promiseSettledResults.filter(p => 'reason' in p)
won't work as expected right without defining your own isRejected
type guard.)
keyIn
keyIn
should be used when you want to narrow the type of key to specific literals.
const a = 'foo';
const obj = {
foo: 1
}
if (a in obj) {
// a is literal type 'foo' now
}
objectHas
objectHas
should be used when you want to safely check the existence of a property? I'm still confused about the use cases of this function.
Pay now to fund the work behind this issue.
Get updates on progress being made.
Maintainer is rewarded once the issue is completed.
You're funding impactful open source efforts
You want to contribute to this effort
You want to get funding like this too