代码之家  ›  专栏  ›  技术社区  ›  theMayer

TypeScript类通用参数约束

  •  1
  • theMayer  · 技术社区  · 6 年前

    我试图声明一个带有受约束泛型参数的TypeScript类。在C#中,将编译以下内容:

    public class NewClass<T> where T: BaseClass {
    }
    

    TypeScript等效于什么?

    2 回复  |  直到 6 年前
        1
  •  4
  •   Sefe    6 年前

    对于作为基础的类和接口,您必须约束 T 像这样:

    export class NewClass<T extends BaseClass> {
    }
    

    当您从接口派生类时 implements ,对于泛型约束,情况并非如此,这使得此代码成为可能:

    export class NewClass<T extends BaseInterface> implements BaseInterface {
    }
    
        2
  •  4
  •   CRice    6 年前

    你在找 extends 关键字。可以在泛型参数之后使用它,将其约束为指定类型的子类型。

    因此,您的示例的等效值为:

    class NewClass<T extends BaseClass> {
        // Things...
    }
    

    您可以在 documentation here