简体   繁体   中英

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  

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM