我想知道是否有一种方法可以声明具有默认泛型类型的泛型类:
- 默认情况下允许调用类的方法而不传递参数
- 如果定义了另一个泛型类型,则只有在传递泛型类型的参数时才能调用该方法。
伪代码
class ClassA<MyGenericType = OptionalArgumentType> {
public methodWithGenericArgument(argumentA: MyGenericType): void {
// Do smth
}
}
//
const instanceX = new ClassA();
instanceX.methodWithGenericArgument(); // CORRECT! We use default optional argument type
//
const instanceY = new ClassA<NotOptionalArgumentType>();
instanceY.methodWithGenericArgument(); // ERROR! Compiler should throw an error here, because we defined NOT OPTIONAL type
//
const argumentValue: NotOptionalArgumentType;
const instanceZ = new ClassA<NotOptionalArgumentType>();
instanceZ.methodWithGenericArgument(argumentValue); // CORRECT! We pass argument with required value