Bilow
Bilow

Reputation: 2324

Return type does not include 'undefined' but switch is exhaustive

I do not understand the error in this minimum example

interface List {
    "A": false,
    "B": false,
}

// Function lacks ending return statement and return type does not include 'undefined'.ts(2366)
// Why?
function foo<T extends keyof List>(letter: T): List[T] {
    switch (letter) {
        case "A":
            return false
        case "B":
            return false
    }
}

What value could letter take so that my function returns undefined?

Upvotes: 1

Views: 682

Answers (1)

Pritam Kadam
Pritam Kadam

Reputation: 2527

Following should take care of your use case:

function foo(letter: keyof List): List[typeof letter] {
  switch (letter) {
    case 'A':
      return false
    case 'B':
      return false
  }
}

Upvotes: 2

Related Questions