打字稿:基于输入的返回类型(在接口内)

时间:2020-05-18 14:35:27

标签: typescript generics types interface return

我正在尝试创建一个在接口I3中返回I1的函数,但是I1类型将包含什么? 取决于输入(字符串)。是I1,I1或I1。我尝试使用any和Union,但是不起作用。

也许可以重载,但是如何在下标中定义呢?

interface I1<T>{
   //methodes
}
interface I2<T>{
   //methodes
}

type a = { name: string}
type b = { licence: string, registred: boolean }
type c = { grade: number  }

interface I3<T,U>{
   something: () => I2,
   notWorking: <k extends T> (...Props:k[]) => I1<?> //not working and ? can be an a,b or c depending on the input
}

1 个答案:

答案 0 :(得分:1)

不确定您要实现的目标,但我认为您可以尝试以下方法:

interface I3<T,U>{
   something: () => I2<U>,
   notWorking: <k extends T> (...Props:k[]) => I1<k extends string ? a : k extends number ? b : c> //not working and ? can be an a,b or c depending on the input
}

注意:您忘记了某些东西的返回类型中的泛型类型参数。