from typing import get_args


def optional_type(cls):
    """
    If cls is Optional[X] it returns X else returns None

    >>> optional_type(Optional[str])
    <class 'str'>
    >>> optional_type(Union[str, int])
    >>> optional_type(str)
    """
    types = [t for t in get_args(cls) if not issubclass(t, type(None))]
    if len(types) == 1:
        return types[0]