I have a variety of types that I need to work with. For example:
type Type = {
prop1: number;
prop2: string;
prop3: someOtherType
}
type Props = keyof Type
I am aware that using an "indexed access type" allows me to extract the type of propN, like this: type Num = Type["prop1"]
. However, my goal is to incorporate this into a function as follows:
function(p: Props) {
// ...
let something = somethingElse as Type[p]
// Typescript struggles to infer the type
// ...
}
Ultimately, I would like to be able to call the function like this:
let a = function("prop1");
// a should be of type number
Unfortunately, this approach is not feasible and results in the error message:
'p' refers to a value, but is being used as a type here. Did you mean 'typeof p'?
If I switch to using typeof p
, then Type[typeof p]
yields the union type number | string | someOtherType
.
I have explored options such as generics, but it seems that they may not provide a solution to this issue.