Skip to content

Describe function signature using an interface  #34319

Open
@fabiancook

Description

@fabiancook

Search Terms

function implements interface

Suggestion

Allow functions to indicate interfaces that they implement, allowing usage of a function interface.

Properties defined on an interface would not be possible unless they are defined as optional

Use Cases

When using function overloads, the return type is defined as any, this would allow the return type to be guarded and not use any. Referencing: https://www.typescriptlang.org/docs/handbook/functions.html#overloads

It would also allow optional properties to be defined on a function without doing type gymnastics.

Examples

interface CoolFunction {
  (first: string, second: number): number;
  (first: number, second: string): string;
  property?: boolean;
}

// args will be of type   [string, number] | [number, string]
function coolFunction(...args) implements CoolFunction {
  if (typeof args[0] === "string") {
    // We're now reduced our type of args to [string, number]
    return args[1];
  } else {
    // args can only be [number, string]
    return args[1];
  }
}

// This property is known as it is defined on the interface
coolFunction.property = true;

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, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

Metadata

Metadata

Assignees

No one assigned

    Labels

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions