Skip to content

generate function declaration from function type in TypeScript #22395

Open

Description

@mjbvz

From Homa Wong (@unional) on October 5, 2017 18:52

type MyCallback = (a: number, b: string) => void

function foo(callback: MyCallback) {
  // ...
}

// case 1
foo((a, b) => { ... })

// case 2
foo(function (a, b) { ... })

// case 3
function cb(a: number, b: string) { ... }
foo(cb)

Above are 3 common ways to write a callback.
TypeScript is great at inferring the argument types in the implemented callbacks.
a, and b are typed accordingly in the callbacks above.

However, the tooltip is not useful when we are implementing the callbacks:

image

If I change foo() to not using type alias, it helps in case 1 and 2:

function foo(callback: (a: number, b: string) => void) { ... }

image

But that doesn't help in case 3 and actually demotes type alias.

One solution I can think of is using [ctrl+.] to fill in the callback:

foo(/* caret */)

// [ctrl+.] and choose "implement callback as arrow function":
foo((a: number, b: string) => { /* caret */ })

// [ctrl+.] and choose "implement callback as function declaration":
foo(function (a: number, b: string) { /* caret */ })

// caret anywhere on the type alias below
MyCallback

// [ctrl+.] and choose "implement function declaration" will expand to snippet:
function ${1:functionName}(a: number, b: string): void { ${0} }

Copied from original issue: microsoft/vscode#35635

Activity

  1. removed their assignment
    on Mar 8, 2018
  2. ackvf commented on Apr 10, 2022

    @ackvf

    This is really great! It's sometimes hard to follow the hints, having TS write a new arrow function in there for me with all the parameters leaving me only to write the function body is just great 🤩

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Domain: LS: Quick FixesEditor-provided fixes, often called code actions.Experience EnhancementNoncontroversial enhancementsIn DiscussionNot yet reached consensusSuggestionAn idea for TypeScriptVS Code TrackedThere is a VS Code equivalent to this issue

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions