Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript infer Generic types from Implementation

So I am working on a react-native project. I was hoping if one could infer Generic types from implementation.

type itemType<T> = { item: T };

const someItem = {
    item: 'Some String'
};

type someItemType = typeof someItem;
// So Here someItemType will be {item: string}, i want it to be itemType<string> and 
// in this example i have implemented itemType but in real use case i want to infer 
//it from the actual implementation  
like image 539
Amol Gupta Avatar asked Nov 22 '18 08:11

Amol Gupta


People also ask

How do you pass a generic type as parameter TypeScript?

Assigning Generic Parameters By passing in the type with the <number> code, you are explicitly letting TypeScript know that you want the generic type parameter T of the identity function to be of type number . This will enforce the number type as the argument and the return value.

How does TypeScript infer types?

TypeScript infers types of variables when there is no explicit information available in the form of type annotations. Types are inferred by TypeScript compiler when: Variables are initialized. Default values are set for parameters.

How do you define a generic type in TypeScript?

Generics allow creating 'type variables' which can be used to create classes, functions & type aliases that don't need to explicitly define the types that they use. Generics makes it easier to write reusable code.

How do I use generic classes in TypeScript?

TypeScript supports generic classes. The generic type parameter is specified in angle brackets after the name of the class. A generic class can have generic fields (member variables) or methods. In the above example, we created a generic class named KeyValuePair with a type variable in the angle brackets <T, U> .


1 Answers

Partial inference on variables is not supported at present in typescript. Your only option is to use the inference behavior of function:

type itemType<T> = { item: T };
const createItemType = <T>(o: itemType<T>) => o;

const someItem = createItemType({ //someItem is typed as itemType<string>
    item: 'Some String'
})

Just one note, it might not matter that in your original example someItem is typed as {item: string}, it will still be assignable to itemType<string> because typescript uses structural compatibility to determine assignability. So if the structure is compatible all is ok:

type itemType<T> = { item: T };

const someItem ={ 
    item: 'Some String'
}
const someOtherItem: itemType<string> = someItem // ok
like image 133
Titian Cernicova-Dragomir Avatar answered Oct 13 '22 19:10

Titian Cernicova-Dragomir