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?