简体   繁体   中英

Typescript: return type based on input (within an interface)

I'm trying to create a function that returns I1 in interface I3, but what does the type I1 is going to contain?. That depends on the input (a string). It is I1, I1 or else I1. I tried using any and Unions but it doesn't work.

Maybe an overload will work, but how can I define that in the inferface?

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
}

Don't understand exactly what you want to achieve but I think you can try something like this:

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
}

Note: You forgot the generic type parameter in the return type of something.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM