Skip to content

Instantly share code, notes, and snippets.

@elnygren
Last active January 12, 2022 09:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elnygren/ddd28c2f0d737d8a1130da783426fea7 to your computer and use it in GitHub Desktop.
Save elnygren/ddd28c2f0d737d8a1130da783426fea7 to your computer and use it in GitHub Desktop.
TypeScript type guard for ensuring / asserting specific optional property
/** Interface with optional properties */
interface IOptionalData {
foo?: { bar?: string };
other?: { bar?: string};
always: { bar?: string };
}
/** Make certain keys of a type required */
type RequiredKeys<T, K extends keyof T> = Exclude<T, K> & Required<Pick<T, K>>
/** Typeguard for property 'foo' in IOptionalData */
const ensureFooProperty = (data: IOptionalData): data is RequiredKeys<IOptionalData, 'foo'> =>
!!data.foo && typeof data.foo.bar === 'string'
const accessData = (data: IOptionalData) => {
if (ensureFooProperty(data)) {
console.log(data.always.bar) // always is always defined
console.log(data.other.bar) // COMPILER ERROR: 'other' is possibly undefined
return data.foo.bar // accessing optional props is allowed due to ensureToFoo
}
console.log(data.foo.bar) // COMPILER ERROR: 'foo' is possibly undefined
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment