Allow me to elaborate on the current scenario:
- I am utilizing the
add
method fromcollection
in Firestore to create a new document - For maintaining type safety with TypeScript, I employ the
withConverter
- When creating a new document, my object does not initially have an ID property
- Once the object is created, the ID property is then available
By the way, Mobx-state-tree is being utilized
The code
Let's go through it step by step
The Company model defined using mobx-state-tree
const CompanyModel = types.model({
id: types.identifier,
name: types.string
});
The required Types
Following the call of the add
method, the CompanyReference is what I receive from Firestore
type CompanyReference = firebase.firestore.DocumentReference<
Instance<typeof CompanyModel>
>;
TCompanySnapshot represents what is sent to Firestore when using the add
method
type TCompanySnapshot = Omit<SnapshotIn<typeof CompanyModel>, "id">;
Converting to and from Firestore using withCOnverter
- Send data to Firestore using the regular
TCompanySnapshot
object - Receive some object from Firestore (now with the ID property) and convert it into
CompanyModel
const createCompanyConverter: firebase.firestore.FirestoreDataConverter<Instance<
typeof CompanyModel
>> = {
toFirestore(modelObject: TCompanySnapshot): firebase.firestore.DocumentData {
return modelObject;
},
fromFirestore(
snapshot: firebase.firestore.QueryDocumentSnapshot<TCompanySnapshot>,
options: firebase.firestore.SnapshotOptions
): Instance<typeof CompanyModel> {
const data = snapshot.data(options);
return CompanyModel.create({
id: snapshot.id,
...data
});
}
};
The issue
Now, when attempting to create a method for adding a new company, a typing error occurs
function addCompany(
// companyData: SnapshotIn<typeof CompanyModel>,
companyData: TCompanySnapshot
): Promise<CompanyReference> {
const added = firestore
.collection("companies")
// .withConverter<Instance<typeof CompanyModel>>(createCompanyConverter)
.withConverter<TCompanySnapshot>(createCompanyConverter)
.add(companyData);
return added; // <<<<<------ ERROR HERE
}
The 'id' property is missing in the type
You can view this error on CodeSandbox
https://codesandbox.io/s/firebase-typescript-mobx-state-tree-n9s7o?file=/src/index.ts