Skip to content

Generics interface conditional type #40104

Closed

Description

@mokeyish

Search Terms

Generics conditional type

Suggestion

interface Array<T> { 
     // allow for all type
     some(callbackfn: (value: T, index: number, array: T[]) => unknown, thisArg?: any): boolean;
}

interface  Array<T when T is number> {
    // only when `T` is number
    sum(): number;
    avg(): number;
    max(): number;
    min(): number;
}

Use Cases

const a = ['a', 'c', 'd'];
// a.sum()   // not allowed

const b = [1, 2, 5];
const c = b.sum(); // ok
console.log(c); // 8

Examples

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.

Activity

  1. changed the title [-]Generics conditional type[/-] [+]Generics interface conditional type[/+] on Aug 18, 2020
  2. MartinJohns commented on Aug 18, 2020

    @MartinJohns
    Contributor

    What about Array<string | number>?

  3. mokeyish commented on Aug 18, 2020

    @mokeyish
    Author

    What about Array<string | number>?

    I write some extension methods for Array, but it is not work as expectedly.

    图片

  4. mokeyish commented on Aug 18, 2020

    @mokeyish
    Author

    Currently , interface declarations with the same qualified name, it Declaration Merging

    https://github.com/microsoft/TypeScript/blob/master/doc/spec.md#7.2

  5. MartinJohns commented on Aug 18, 2020

    @MartinJohns
    Contributor

    Please note that the spec is completely outdated and abandoned.

  6. RyanCavanaugh commented on Aug 19, 2020

    @RyanCavanaugh
    Member

    You can already do this today; no new syntax is necessary:

    interface  Array<T > {
        sum(this: Array<number>): number;
    }
    
    declare const a: string[];
    a.sum(); // Error
    declare const b: number[];
    b.sum(); // OK
  7. mokeyish commented on Aug 19, 2020

    @mokeyish
    Author
  8. locked as resolved and limited conversation to collaborators on Oct 21, 2025
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

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions