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]>
CodePudding user response:
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