Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Use conditional type to narrow return type of function with a union-typed argument #24929

Copy link
Copy link
@aneilbaboo

Description

@aneilbaboo
Issue body actions

Search Terms

conditional return type narrowing generics

Suggestion

It seems like it should be possible to constrain the return type of a function using a conditional expression:

For example,

// I want my function to have a different return type depending on input
export function foo<T extends string|number>(
  val: T                                  // input type is a union
): T extends string ? string : number {   // output type is either string or number
  return val;
} 
// expected this to work, but received:
// Type 'T' is not assignable to type 'T extends string ? string : number'.
//  Type 'string | number' is not assignable to type 'T extends string ? string : number'.
//    Type 'string' is not assignable to type 'T extends string ? string : number'.

Use Cases

A common use case is a function which can process single objects or arrays of objects, and returns single objects or an array, respectively.

Examples

// capitalize a string or each element of an array of strings
function capitalize<T extends string | string[]>(
  input: T
): T extends string[] ? string[] : string {
  if (isString(input)) {
    return input[0].toUpperCase() + input.slice(1);
  } else {
	return input.map(elt => capitalize(elt));
  }
}

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)
Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already createdAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.