FredyC
FredyC

Reputation: 4067

Different return type based on boolean argument

I know there are a few similar-looking questions, but I haven't seen a solution there.

type ID = string
type MaybeID = ID | null

const defaultBranchId: ID = "1"
const currentBranchId: MaybeID = null

export function useBranchFilter1(withDefaultBranch = true) {
  if (currentBranchId === null && withDefaultBranch === true) {
    return defaultBranchId
  }
  return currentBranchId
} // <-- infers to MaybeID return type

I am expecting to always get ID return type.

Here is the playground link with a few attempts I've tried - unsuccessfully.

Feels like a simple thing, but I am expecting it can't work like that since it's based on runtime value.

Upvotes: 0

Views: 46

Answers (1)

Murat Karag&#246;z
Murat Karag&#246;z

Reputation: 37624

The return type is correct. There are two return types, one is string the other null which fits the type MaybeID since type ID = string.

Upvotes: 1

Related Questions