Skip to content

Add support for Typescript Custom Mapping #2240

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 37 commits into from
Dec 10, 2019
Merged

Add support for Typescript Custom Mapping #2240

merged 37 commits into from
Dec 10, 2019

Conversation

thebrianchen
Copy link

@thebrianchen thebrianchen commented Oct 4, 2019

API proposal: internal link

Fixes #1888 via a withConverter() methods on CollectionReference, DocumentReference, and Query that allow developers to use Firestore classes with generics.

Example usage:

class Post {
  constructor(readonly title: string, readonly author: string) {}
  byline(): string {
    return this.title + ', by ' + this.author;
  }
}

const PostConverter = {
  toFirestore(post: Post): DocumentData {
    return {title: post.title, author: post.author};
  },
  fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {
    const data = snapshot.data(options)!;
    return new Post(data.title, data.author);
  }
};

const postSnap = await firebase.firestore().collection('posts').withConverter(PostConverter).doc().get();
const post = postSnap.data();
if (post !== undefined) {
  post.title; // string
  post.byline(); // Should be defined 
  post.someNonExistentProperty; // TS error
}

@thebrianchen thebrianchen changed the title WIP generics Add support for Typescript Custom Mapping Nov 20, 2019
Copy link
Contributor

@mikelehen mikelehen left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After a final review I found just a few more minor things to nit, but this looks really good to me. Thanks for all the effort that went into it. I think it came out pretty slick. Hopefully users agree. 😄

@mikelehen mikelehen assigned thebrianchen and unassigned mikelehen Dec 4, 2019
@thebrianchen
Copy link
Author

Also went over the docs with Mark, and updated docs after his review.

@thebrianchen thebrianchen merged commit f9d26f7 into master Dec 10, 2019
@thebrianchen thebrianchen deleted the bc/generics branch December 10, 2019 01:46
@hsubox76 hsubox76 added this to the next milestone Dec 10, 2019
@firebase firebase locked and limited conversation to collaborators Jan 9, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

FR: Generic Document Types
4 participants