【发布时间】: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