Try to get type of properties of an object based on the following typescript tutorial link but it acts like javascript and returns value of the property instead of the type:
const x = { foo: 10, bar: 'hello!' };
const foo = getProperty(x, 'foo'); // number
console.log(foo);
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key]; // Inferred type is T[K]
}
but it shows the value 10 instead of type number for example. Any idea?
To clarify, please look into the following link, which is about TypeScript keyof and Lookup Types, I expect the above code in typescript angular component returns the type of property, not the value of that:
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-1.html
typeof obj[key]if you want its type.obj[key]is what it is, the value for that key. - Jetoobj[key].constructor.namethen? See stackblitz.com/edit/angular-cjcxa6 (only main.ts is used, check browser console) for an example. I'm fairly new to TypeScript so sorry if that's obvious (object.constructoris just JS though). - Jeto