The difference is that in the first case the return type will be T[K]
while in the second case it will be T[keyof T]
. K
can at it's widest be keyof T
but it can be a specific string literal type representing a key. This means if K
is a specific property the return value will be of the same type as the property:
function prop<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}
function prop2<T>(obj: T, key: keyof T) {
return obj[key];
}
let o = {
p1: 0,
p2: ''
}
let v = prop(o, 'p1') // is number, K is of type 'p1'
let v2 = prop2(o, 'p1') // is number | string, no extra info is captured
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…