buape / carbon

A fully-featured HTTP library for Discord bots
https://carbon.buape.com/
MIT License
9 stars 5 forks source link

Add type parameters to partial structures #101

Closed thewilloftheshadow closed 5 minutes ago

thewilloftheshadow commented 3 days ago

Add type parameters to Partial structures so that things like fetchGuild() will return Guilds that are for sure not partial, since we fetched the data before

(Maintainers, see https://discord.com/channels/1280628625904894072/1284942028685443144/1284955904822870168)

apteryxxyz commented 3 days ago

I'm gonna post the mock I made as reference.

import { APIUser } from 'discord-api-types/v10'

// i tried using boolean before, but went with this due to issues with the value type being expanded to boolean
// tho as im making this comment i realised might be able to add const to the type parameter
export class User<D extends string | APIUser> {
    private _data: Partial<APIUser>

    constructor(data: D) {
        if (typeof data === 'string') this._data = { id: data }
        else this._data = data
    }

    get id() {
        return this._data.id!
    }

    get globalName(): D extends string ? undefined : string {
        // would have to always type case due to the condition, tho i think only internally, user wont have to
        return (this._data.global_name || undefined) as never
    }
}

const user = new User('aaaaa')
user.globalName
//     ^? undefined

const user2 = new User({} as APIUser)
user2.globalName
//      ^? string
apteryxxyz commented 2 days ago

I tried a bunch of ways of using IsPartial extends boolean , but at the moment can only get D extends string | APIUser to work, bit annoying but oh well