Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type '"test"' cannot be used to index type 'T'

Tags:

typescript

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.

like image 830
kraftwer1 Avatar asked Aug 07 '17 11:08

kraftwer1


People also ask

What has any type because expression of type any Cannot be used to index type?

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.

What is T in typescript type?

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.


1 Answers

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] {}
like image 83
Madara's Ghost Avatar answered Sep 23 '22 11:09

Madara's Ghost