mercredi 5 août 2020

Impossible fallback return cause a coverage issue. Ts error otherwise

type Status = "default" | "hover" | "active" | "disabled"
type StatusMap = {
    [key in Status]?: boolean
}
const stack: Status[] = ['disabled', 'active', 'hover', 'default']
function getStatus(props: StatusMap): Status {
    for (let i = 0; i <= stack.length; i++) {
        const s = stack[i]
        if (props[s]) {
            return s
        }
    }
}

Here is the ts code which causes the problems:

Function lacks ending return statement and return type does not include 'undefined'

Ts believe there is a chance to return undefined, However it is not possible in a real use case. Because at least one key will present in StatusMap even though it is noted as optional.

Maybe a quick fix is to return a default value so that ts will not complain. However, the default return will never be hit which causes a coverage issue.

What is the possible solution

Aucun commentaire:

Enregistrer un commentaire