Reputation: 2554
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
Upvotes: 6
Views: 149
Reputation: 249466
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
Upvotes: 4
Reputation: 250812
It doesn't matter whether the type is defined as { item: string }
or itemType<string>
as TypeScript uses structural typing. That means the two are the same, because they have identical structures.
For example, you can assign values of either type to each other type:
type itemType<T> = { item: T };
const someItem = {
item: 'Some String'
};
type someItemType = typeof someItem;
const a: itemType<string> = { item: 'exmaple a' };
const b: someItemType = { item: 'exmaple b' };
let c: itemType<string>;
c = a;
c = b;
let d: someItemType;
d = a;
d = b;
Upvotes: 2