Any idea how this can be achieved?
function getTest<T>(): T["test"] {
// ...
}
...or dynamically:
function getTest<T, U>(): T[U] {
// ...
}
Unfortunately, the compiler says Type '“test”' cannot be used to index type 'T'
. I'm using TypeScript 2.4.2.
The error "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type" occurs when we use a string to index an object with specific keys. To solve the error, type the string as one of the object's keys.
This article opts to use the term type variables, coinciding with the official Typescript documentation. T stands for Type, and is commonly used as the first type variable name when defining generics. But in reality T can be replaced with any valid name.
Note that for type inference to work, you'll need to pass a parameter to the function that uses one or more of the generic type parameters.
Otherwise, it will be inferred to {}
or any
.
For the first case:
function getTest<T, U extends {test: T}>(): T {}
For the second case:
function getTest<T, K extends keyof T>(): T[K] {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With