1
votes

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

1
That code does exactly what i expect it to do. - H.B.
You need to return typeof obj[key] if you want its type. obj[key] is what it is, the value for that key. - Jeto
@Jeto :: Not actually, You would get a return value of the type "string" | "number" | "boolean" | "symbol" | "undefined" | "object" | "function", because you're using the JavaScript typeof operator at runtime, which returns a string like "object", not the compile-time type seen by TypeScript. - Farhad
@Farhad True, but what about obj[key].constructor.name then? 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.constructor is just JS though). - Jeto

1 Answers

0
votes

You can use this pattern with other parts of the type system to get type-safe lookups

...is what was stated, which is this: Getting property values.

If you want to get type information you have to use things like reflect-metadata. Not sure if the emission of this information can be fully automated though. Types in TypeScript only exist before compilation, so without using some kind of annotation system, there is no way of getting that information during run time.

You can of course always get the type of a value using typeof (could be added to the function above) but you will always need an instance of the class and the property has to be set to a valid value.