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
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.
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.
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.
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> .
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
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