【问题标题】:Typescript generics: how to ensure function args match each other?Typescript 泛型:如何确保函数 args 相互匹配?
【发布时间】:2020-03-23 19:10:11
【问题描述】:

我想要一个具有某种类型的 arg 和“匹配”文字的函数。我该怎么做?

class T1 {
  val: string = "abc"
}
class T2 {
  val: number = 123
}
type TType = 'T1' | 'T2'

// I want to make this generic so the args have to "match"
function foo(ttype: TType, arg: T1 | T2) {
  console.log(`${ttype}: arg.val`)
}

foo('T1', new T1)
foo('T2', new T2)
foo('T1', new T2) // I want this to be a compile-time error

我希望代码要求当“T1”作为ttype 传递时,需要 T1 类型的对象作为第二个参数,反之亦然。如果可以避免这种情况(不想复制正文),我不想要该函数的两个版本——只是一个类型规范,上面写着“文字 T1 和 T1, 文字T2 和 T2"。我很高兴手动设置映射——我不需要从字符串文字中获取类名。只是不知道如何在 Typescript 中处理这个问题。

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    最简单的方法是使用重载

    function foo(ttype: "T1", arg: T1): void
    function foo(ttype: "T2", arg: T2): void
    function foo(ttype: TType, arg: T1 | T2) {
      console.log(`${ttype}: arg.val`)
    }
    
    

    Playground Link

    您也可以使用带有映射接口的通用函数,但对于这个例子来说可能有点矫枉过正:

    type TMap = {
      "T1": T1
      "T2": T2
    }
    // I want to make this generic so the args have to "match"
    function foo<T extends TType>(ttype: T, arg: TMap[T]): void
    function foo(ttype: TType, arg: T1 | T2) {
      console.log(`${ttype}: arg.val`)
    }
    
    

    Playground Link

    【讨论】:

    • 完美——重载正是我所需要的。没想到他们是这样工作的。谢谢!
    猜你喜欢
    • 2023-02-10
    • 1970-01-01
    • 2020-11-15
    • 2018-07-03
    • 2018-10-23
    相关资源
    最近更新 更多