简体   繁体   中英

How to narrow down Firestore Field Value

background:

I am creating a typesafe wrapper for firestore, the wrapper can now type safe every kind of data type and all operations

the wrapper: https://www.npmjs.com/package/firelord

==============

The problem:

however, there is one particular data type that I cant safely type it, that is Firestore.FieldValue (increment, servertimestamp, arrayunion, arrayremove)

it seems like it is impossible to narrow down this thing, which is quite frustrating

I cant found any solution to this which lead me to think how does people handle FieldValue all these time or do they just yolo it?

The current solution that I have in mind now is, I create a helper function, for example, arrayUnion

        const arrayUnion = <T>(value: T) => {
            return firestore.FieldValue.arrayUnion(value) as unknown as T[]
        }

Then it will match the data type defined.

I think this should work, however is there any better way to do it? Is narrowing down Firestore.FieldValue possible at all?

I am seriously looking for a sensible solution as this is the final piece of the puzzle to make my firestore wrapper completely type safe and scalable

const increment = (value: number) => {
    return firestore.FieldValue.increment(value) as unknown as {
        'please import `increment` from `firelord` and call it': number
    }
}

const serverTimestamp = () => {
    return firestore.FieldValue.serverTimestamp() as unknown as {
        'please import `serverTimestamp` from `firelord` and call it': 'ServerTimestamp'
    }
}

const arrayUnion = <T>(...values: T[]) => {
    return firestore.FieldValue.arrayUnion(...values) as unknown as {
        'please import `arrayUnion` or `arrayRemove` from `firelord` and call it': T
    }
}
const arrayRemove = <T>(...values: T[]) => {
    return firestore.FieldValue.arrayRemove(...values) as unknown as {
        'please import `arrayUnion` or `arrayRemove` from `firelord` and call it': T
    }
}

I decided to go with this solution, similar to what I proposed in my question

However I masked it with objects literal that looks weird, this is to prevent users from accidentally using it for another purpose

theoretically, it is not 100% safe, but in practice this should be safe enough

with this my firestore wrapper is finally complete, time to end the yolo-ing

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