Skip to content

Function return type is not implied conditionally based on type of parameter #30262

@joshuafairchild1

Description

@joshuafairchild1

TypeScript Version: 2.9.2

Search Terms:
typescript return type based on parameter
Code

type StringOrNull<B extends Boolean> = B extends true ? string : (string | null)
type StringNotNull = StringOrNull<true>

function foo<B extends boolean>(returnString: B): StringOrNull<B> {
  if (returnString) {
    return '' as StringNotNull // type error: "Type 'string' is not assignable to type 'StringOrNull<B>'"
  } else {
    return null
  }
}

Expected behavior:

Typecast should be valid, with the return type of foo being:

  • string when returnString is passed as true
  • string | null when returnString is passed as false

Actual behavior:
Cast cannot succeed, and return type is not dynamic based on the boolean passed to foo

Playground Link:
https://www.typescriptlang.org/play/#src=type%20StringOrNull%3CB%20extends%20Boolean%3E%20%3D%20B%20extends%20true%20%3F%20string%20%3A%20(string%20%7C%20null)%0D%0Atype%20StringNotNull%20%3D%20StringOrNull%3Ctrue%3E%0D%0A%0D%0Afunction%20foo%3CB%20extends%20boolean%3E(throwError%3A%20B)%3A%20StringOrNull%3CB%3E%20%7B%0D%0A%20%20if%20(throwError)%20%7B%0D%0A%20%20%20%20throw%20Error()%0D%0A%20%20%7D%0D%0A%20%20return%20''%20as%20StringNotNull%0D%0A%7D

Related Issues:

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions