Search code examples
typescriptcastingdiscord.jstypescript-typings

Typescript preventing simple length check as conditional conceals helpful methods and properties


This is a typescript question using discord.js as an example, no need to understand the library to help.

I'm converting my app from normal js, when I call a method it gives me a map type with a key and value. Now that I am using typescript and the library has type definitions, I can no longer check the size of the response.

const attachments = interaction.options.getMessage('message', true).attachments;

So previously I could just call a size property but now I am restricted to these types:

attachments: Collection<string, MessageAttachment> | APIAttachment[]

Is it bad practise to just chose one of the conditionals by using the as keyword so I have more properties to play with? How can I get the size of attachments or safely resolve to one type? They only have iterators.

I understand the benefits of typescript and am avoiding any hacky solutions. I'm trying to learn to work better with typescript and want to use the types that the library has given me.


Solution

  • I would recommend this simple fix

    You could do something like:

    If you want the attachments to be a collection

    import { Collection } from "discord.js"
        
    if(attachments instanceof Collection){
        // Do this
    }
    

    or if you want the attachments to be a array

    import { Collection } from "discord.js"
    
    if(!(attachments instanceof Collection)){
        // Do that
    }
    

    TypeScript will then automatically detect attachments to be an array or collection