Im trying to get the correct return type based on the method key of an interface. Typescript is showing an issue here but i cant work out why.
interface Provider {
reboot?(a: string): (string | null)[]
cc?(): Promise<string>
}
type ProviderReturn<K extends keyof Provider> = ReturnType<Provider[K]>
Your interface defines an object with 2 potentially undefined methods. ReturnType
does not work on undefined
You can do follwing with Nonnullable
interface Provider {
reboot?(a: string): (string | null)[]
cc?(): Promise<string>
}
type ProviderReturn<K extends keyof Provider> = ReturnType<NonNullable<Provider[K]>>
If the optional part matters, you can use a conditional type:
interface Provider {
reboot?(a: string): (string | null)[]
cc?(): Promise<string>
foo(): string
}
type ProviderReturn<K extends keyof Provider> = undefined extends Provider[K] ? ReturnType<NonNullable<Provider[K]>> | undefined : ReturnType<NonNullable<Provider[K]>>
type a = ProviderReturn<'reboot'> // (string | null)[] | null;
type b = ProviderReturn<'foo'> // string
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.