Skip to content

Reference class type parameters in static members #32246

Closed
@ardalanamini

Description

@ardalanamini

Search Terms

static, generic, type, class, model, inheritance

Suggestion

Static class members should be allowed to reference the class's type parameters.

Use Cases

A very simple use case is in database models such as the example given below.
At the moment there's no way provided by the TypeScript to deal with such a problem which is the main reason we use this language, type safety!

Examples

Expected behavior:

class Model<T extends object = any> {
  public static all(): Promise<T[]> {
    // code
  }

  public static first(): Promise<T> {
    // code
  }
}

class User extends Model<{ username: string }> {}

User.all(); // Promise<Array<{ username: string }>>
User.first(); // Promise<{ username: string }>

The behavior we got to deal with: (which can add more typing error easily)

class Model {
  public static all<T extends object = any>(): Promise<T[]> {
    // code
  }

  public static first<T extends object = any>(): Promise<T> {
    // code
  }
}

class User extends Model {}

User.all<{ username: string }>(); // Promise<Array<{ username: string }>>
User.first<{ username: string }>(); // Promise<{ username: string }>

This bahavior is unacceptable since it needs the developer to reference the item interface every time he/she calls these sort of methods, which doesn't seem to satisfy the soul purpose of the TypeScript

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

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions