Skip to content
This repository has been archived by the owner on Dec 31, 2020. It is now read-only.

Is it possible to make Provider and @inject type safe? #143

Closed
mohsen1 opened this issue Oct 29, 2016 · 4 comments
Closed

Is it possible to make Provider and @inject type safe? #143

mohsen1 opened this issue Oct 29, 2016 · 4 comments

Comments

@mohsen1
Copy link

mohsen1 commented Oct 29, 2016

Currently Provider and @inject are using strings for providing stores and injecting them in components. Is it possible to use TypeScript generics to make sure that those strings are type checked by TypeScript compiler? Since strings can be their own types in TypeScript it should be possible to take advantage of that feature.

@mohsen1
Copy link
Author

mohsen1 commented Oct 29, 2016

If Provider was a generic as described here it would be possible to make a custom type of all injected props with type operator

export type stores = 'store1' | 'store2';

interface MyStoresProviderInterface { new (): Provider<stores> } ;
const MyStoresProvide = Provider as MyStoresProviderInterface;

const provided = <MyStoresProvide store1={store1} store1={store2} />

Then later when injecting

import stores from './app.ts' // 'store1' | 'store2

typedInject = (store: stores) => inject.bind(inject, store)

@typedInject('store1'); // this will make sure string 'store1' is type safe

I don't know TypeScript well enough to say this is a proper way of making Provider and @inject type safe, any ideas?

@mweststrate
Copy link
Member

@mohsen1, I don't think your example will work (especially as strong typing Provider is actually not very interesting, it is on inject where you want to get the proper types). I think the closest way to get there is described here: https://github.com/mobxjs/mobx-react#strongly-typing-inject.

If you feel it can be better typed, feel free to submit a PR!

@mohsen1
Copy link
Author

mohsen1 commented Oct 31, 2016

I liked the example in README but it's not as type safe as it should be. When you use as it's not really strictly typed! :)

If Provider and inject where under the same class, we could make that class a generic of store types:

class MobXReact<StoreType[]> {
    public Provider(...stores: StoreType[]) {
        return Provider.bind(Provider, ...stores); 
    }

    public inject(...stores: StoreType[]) {
        return inject.bind(inject, ...stores)
    }
}

But those are two independent functions that can't really share generic types without a bridge.

@mweststrate
Copy link
Member

Yep, and there might be many different configs of Provider and inject in the same app. Unless somebody has a genius idea, I do't think this is feasible

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants