You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Is your feature request related to a real problem or use-case?
Type guards for objects are done using the in operator. However it doesn't provide autocompletion and doesn't show an error if the tested property is not part of the object.
interfaceA{a?: number;}interfaceB{b: number;}constobj={a: 1}asA|B;if("invalid"inobj){console.log(obj.invalid);// invalid is typed as "unknown"}
Describe a solution including usage in code example
I propose to add two functions, I provide the implementation I'm using in personal projects.
typeKeysOf<T>=TextendsT ? keyofT : never;typeExtractByKey<T,KextendsKeysOf<T>>=Extract<T,{[PinK]?: any}>;exportfunctionhasProperty<Textendsobject,KextendsKeysOf<T>>(obj: T,key: K,): obj is ExtractByKey<T,K>{returnkeyinobj;}if(hasProperty(obj,"a"){// autocompletion is providedconsole.log(obj.a);// `a` is `number | undefined` because it's optional}if(hasProperty(obj,"invalid"){// type error hereconsole.log(obj.invalid);}
typeExtractByKeyAndAssertNonUndefined<T,KextendsKeysOf<T>>=&ExtractByKey<T,K>&{[PinK]: Exclude<T[P],undefined>};exportfunctionhasValue<Textendsobject,KextendsKeysOf<T>>(obj: T,key: K,): obj is ExtractByKeyAndAssertNonUndefined<T,K>{returnkeyinobj&&obj[key]!==undefined&&obj[key]!==null;}if(hasValue(obj,"a"){console.log(obj.a);// `a` is `number`}
Who does this impact? Who is this for?
TypeScript users
The text was updated successfully, but these errors were encountered:
hasValue implementation is good, but the name needs refinement as it's not obvious it's reffering to the object property defined value. Please propose some alternatives.
Thanks
Is your feature request related to a real problem or use-case?
Type guards for objects are done using the
in
operator. However it doesn't provide autocompletion and doesn't show an error if the tested property is not part of the object.Describe a solution including usage in code example
I propose to add two functions, I provide the implementation I'm using in personal projects.
Who does this impact? Who is this for?
TypeScript users
The text was updated successfully, but these errors were encountered: