Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between of "K extends keyof T" vs. directly using "keyof T"?

Tags:

Is there any difference between the following typescript definitions:

function prop<T, K extends keyof T>(obj: T, key: K) {
    return obj[key];
}

and

function prop2<T>(obj: T, key: keyof T) {
    return obj[key];
}

I mean no, but maybe I have overseen something. Are there any benefits to use the first version (which is often used in the docs)

like image 804
loxy Avatar asked Nov 01 '18 10:11

loxy


People also ask

What does keyof typeof do?

keyof is a keyword in TypeScript which is used to extract the key type from an object type.

What does Keyof return?

keyof T returns a union of string literal types. The extends keyword is used to apply constraints to K, so that K is one of the string literal types only. extends means “is assignable” instead of “inherits”' K extends keyof T means that any value of type K can be assigned to the string literal union types.


1 Answers

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
like image 122
Titian Cernicova-Dragomir Avatar answered Sep 22 '22 19:09

Titian Cernicova-Dragomir