The error message is a helpful hint on how to resolve the issue:
'typeVariable' is referencing a value but is being used as a type in this context.
Did you mean 'typeof typeVariable'?(2749)
In TypeScript, the type system cannot directly operate on values. To address this, you must convert a value to its corresponding type using the typeof
keyword.
const typeVariable = 'CustomType';
type Z = TypeMapper[typeof typeVariable] // equivalent to: type Z = CustomType
If you hover over func
in this line
const z = func<TypeMapper[typeof typeVariable]>(1,2);
You should see that it has the following type:
function func<CustomType>(x: number, y: number): void
This appears to be the desired outcome based on your code.
Playground
I am utilizing a dynamic string variable that is not known at compile time
This presents a challenge because types are only defined during compile time. If the string's value is unknown until runtime, you will need to handle it dynamically.
Consider the following function:
function func1(type_string: string) {
type t = TypeMapper[typeof type_string];
}
You can pass any arbitrary string
into this function, as indicated by its type definition. What would you expect t
to be if you pass in "BadString"
?
To make this scenario work, you must narrow down the type string
to specific types for safe usage detection.
For instance:
function func1(type_string: string) {
if (type_string === 'CustomType') {
type t = TypeMapper[typeof type_string]; // valid operation
} else {
throw new Error(`Unknown type string: ${type_string}`)
}
}
Playground
There are multiple techniques for narrowing types, but without more context from your code snippet, it's challenging to recommend a specific approach.