extract.ts
function extract1<S>(source: S, key: keyof S) {
return source[key]
}
function extract2<S, K extends keyof S>(source: S, key: K) {
return source[key]
}
main.ts
const source = {foo: 1, bar: '2'}
// Type is deduced as `string | number`
const result1 = extract1(source, 'foo')
// Type is deduced as `number`
const result2 = extract2(source, 'foo')
extract1
和extract2
之间有什么区别,为什么可以精确推断出extract2的返回类型,而不能正确推断出extract1?