typescript - 泛型类的可选方法参数的类型

标签 typescript overloading typescript-class generic-type-parameters

我想知道是否有一种方法可以声明具有默认泛型类型的泛型类:

  1. 默认情况下允许调用类的方法而不传递参数
  2. 如果定义了另一个泛型类型,则只有在传递泛型类型的参数时才能调用该方法。

伪代码

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

最佳答案

通过一些技巧,你可以做到这一点。食谱包括:

  1. 从不作为泛型类型参数的默认类型
  2. rest parameters TS 3.0 中添加了元组类型

这个想法是有条件地在空元组和一个参数的元组(或多个或多个条件 - 根据您的实现而疯狂)之间切换。这是这样的:

class ClassA<MyGenericType = never> {
    public methodWithGenericArgument(...args: MyGenericType extends never ? [] : [MyGenericType]): void {
        // Do smth
    }
}

type NotOptionalArgumentType = number;

const instanceX = new ClassA();
instanceX.methodWithGenericArgument(); // OK
instanceX.methodWithGenericArgument(15); // ERROR

const instanceY = new ClassA<NotOptionalArgumentType>();
instanceY.methodWithGenericArgument(); // ERROR
instanceY.methodWithGenericArgument(15); // OK

let argumentValue!: NotOptionalArgumentType;
const instanceZ = new ClassA<NotOptionalArgumentType>();
instanceZ.methodWithGenericArgument(); // ERROR
instanceZ.methodWithGenericArgument(argumentValue); // OK

Playground

关于typescript - 泛型类的可选方法参数的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67522291/

相关文章:

javascript - 是否可以使用 rxjs angular 5 在其他选项卡浏览器中订阅 observable

c++ - 在类外重载运算符

javascript - 在 typescript svelte 中导入别名 svelte 组件

typescript - 如何使用外部 npm 模块返回的 promise

typescript :类型映射类型不能用原始类型索引

java - 为什么输出是int?

c# - 区分重载的泛型方法和非泛型方法

typescript - 在 TypeScript 中,如何创建一个通用函数,根据给定的类名和函数来推断函数的参数?

typescript :在类构造函数中使用 `this` 类型