I have a function that returns whether an object property is undefined
. I need this function instead of just doing obj[key] === undefined
because otherwise I'd sometimes get Property 'foo' does not exist on type 'Bar'.
. It's straightforward to write the type when the property key is a literal. Ie:
function hasDefinedProp<
Obj extends Partial<Record<string, any>>,
Prop extends string,
>(
obj: Obj,
prop: Prop,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
return obj[prop] !== undefined;
}
const obj: Partial<Record<string, number>> = {};
if (hasDefinedProp(obj, 'foo')) {
obj.foo + 1; // No error.
obj.bar + 1; // "Object is possibly 'undefined'."
}
However, this doesn't work when the key's type is a wide type, ie:
const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
obj[key] + 1; // No error.
obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}
Is it possible to make the type guard work for wide types?
AFAIK, it is not possible. Once you have added explicit string<\/code> type to
const key: string = '';<\/code>
- TS is unable to narrow literal type of
key<\/code> .
As a result, you are allowed to use any string you want to access a property. TS is unable to distinguish two types with type
string<\/code> in this example:
const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
obj[key] + 1; // No error.
obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.