Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript generic function param and return type inference

What's the difference between these two function definitions?

With first getProperty, TypeScript can infer the return type. But the second one fails.

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

function getProperty2<T>(obj: T, key: keyof T) {
    return obj[key];
}
let obj = {
    a: 1,
    name: 'test',
}

const name2 = getProperty(obj, 'name');
name2.length;   // This is OK, name2 is infered as string

const name3 = getProperty2(obj, 'name');
name3.length;  // This is ERROR! name3 is of type string | number
like image 210
Jess Avatar asked Dec 22 '25 16:12

Jess


1 Answers

On the first one, K is explicitly defined. So, when you pass name, Typescript can infer the type. However on the second one, getProperty2 function expects any keyof T. So, the return type becomes string | number (if you add more key to obj, this will become more complex). That's why Typescript is not sure which one will you get.

You can fix this by using as as follows since you are sure that you will get a string in return.

const name3 = getProperty2(obj, 'name') as string;
name3.length;
like image 83
Bunyamin Coskuner Avatar answered Dec 24 '25 09:12

Bunyamin Coskuner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!