robkuz
robkuz

Reputation: 9934

Why is a cast needed on generically defined return type?

Given this very simple property access function

export function accessProperty<T, K extends keyof T, P extends T[K]>(name: K, v: T): P {
    return v[name] as P
}

why is the cast as P needed?

I tried variations of it

export function accessProperty<T, K extends keyof T, P = T[K]>(name: K, v: T): P 
export function accessProperty<T, K extends keyof T, P extends T[K] = T[K]>(name: K, v: T): P 

but all require the cast

Upvotes: 0

Views: 25

Answers (1)

brunnerh
brunnerh

Reputation: 185225

The way the generics are defined every P is a T[K], but not necessarily every T[K] is a P. You can fix this by using T[K] directly.

I.e.

export function accessProperty<T, K extends keyof T>(name: K, v: T): T[K] {
    return v[name];
}

Upvotes: 1

Related Questions