microsoft / microsoft/TypeScript

typeof return

Open
#53,900 5 comments 5 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Awaiting More Feedback Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Suggestion

When return type of a function is known, introduce a special keyword which gives access to that return type.

✅ Viability 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. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Introduce a mechanism to use the return type of the current function, when it is known in advance.

📃 Motivating Example

Consider the example below where return type string of function type F is known in advance, but the type F might be unavailable, at least easily. In that case, the return type of the F is known, but there is no alias to make use of it.

There could be a magic alias, say typeof return, which holds the return type of the current function, if that type is defined in advance.

type F = () => string;

const implementF = (implementation: F) => {};

implementF(() => {
  const result: typeof return = 'abc'; // string
  return result;
});

Here return is a reserved keyword in JavaScript, so there should be no identifier named "return".

Basically typeof return would return the type (if known), that would be expected, if there was a ReturnStatement at the place where typeof return was written.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reviewing the TypeScript Design Goals linked in the issue, then analyze how the proposed typeof return should behave for contextually typed function expressions. Done would require a resolved design for the syntax and semantics, including when the return type is known; no implementation files or tests are named.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.