“K extends keyof T"之间的区别还是直接使用“keyof T"? [英] Difference between of "K extends keyof T" vs. directly using "keyof T"?
问题描述
以下打字稿定义之间有什么区别:
Is there any difference between the following typescript definitions:
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];
}
我的意思是不,但也许我监督了一些事情.使用第一个版本有什么好处(文档中经常使用)
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)
推荐答案
区别在于第一种情况下返回类型为 T[K]
而第二种情况下返回类型为 <代码>T[keyof T].K
可以是最宽的 keyof T
但它可以是表示键的特定字符串文字类型.这意味着如果 K
是特定属性,则返回值将与该属性具有相同的类型:
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
这篇关于“K extends keyof T"之间的区别还是直接使用“keyof T"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!