Typescript: How to Use Optional Chaining on Unknown Types

Rating: 3

Typescript does not currently support optional chaining on unknown types. You will need to use a hack such as the one here.

Example

/**
 * Hack that allows us to use ?. optional chaining on unknown types in Typescript.
 *
 * See https://github.com/microsoft/TypeScript/issues/37700#issuecomment-940865298
 */
type Unreliable<T> = { [P in keyof T]?: Unreliable<T[P]> } | undefined;

const decoded = jwt_decode(jwt) as Unreliable<{ session: { identity: { traits: { email: string } } } }>;
const decodedEmail = decoded?.session?.identity?.traits?.email;
More Info