Last active
January 12, 2022 09:44
-
-
Save elnygren/ddd28c2f0d737d8a1130da783426fea7 to your computer and use it in GitHub Desktop.
TypeScript type guard for ensuring / asserting specific optional property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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