xh / hoist-react

🏗️ ⚛️ The XH Hoist toolkit for React
https://xh.io
Apache License 2.0
24 stars 9 forks source link

Support `Store` generic types to spec types for `StoreRecord.data` and `StoreRecord.id` #3691

Open amcclain opened 4 months ago

amcclain commented 4 months ago

It would be excellent if we could spec an interface for the data element of all records within a given Store, so you would have type-aware support when reading their data in code.

Have not thought it through in detail, but I am assuming StoreRecord would take a generic and then Store, GridModel, etc. would have some way to pass it though. And of course it would need to come out the other side of a variety of StoreRecord-emitting APIs. But I believe it would be a big win, given how common it is to pass records around through an application.

Being able to tell TS that your ids will be either numbers or strings (as opposed to either) could also eliminate some common boilerplate casting.

amcclain commented 3 months ago

@haynesjm42 noted that the ability to type record.raw could also be useful. We also discussed the pitfalls of having to carry multiple generics through multiple classes (store, gridmodel, etc) - how to do that in a scalable way.

We could consider a compound type - e.g.

type RecordType<IdType extends StoreRecordId, DataType extends PlainObject, RawType extends PlainObject> = {
    id: IdType;
    data: DataType;
    raw: RawType;
};

class Store<R extends RecordType<any, any, any>> {
    records: R[];
}

// Then in app code....
type PersonRecord = RecordType<number, {name: string, age: number}, {name: string, age: number}>;
const store = new Store<PersonRecord>()
store.records.map(it => it.data.age)