Encountering an issue while developing a Discord bot using TypeScript

Hello, I'm currently working on creating a nick command for my discord bot in TypeScript, but I encountered an error. Here is the issue:

Error: Expression expected.ts (1109)

When I replace

const mentionedMember = message? message.mentions.members?.first():

with

const mentionedMember = message? message.mentions.members?.first(),

It resolves the issue with const nickName = args.slice(1).join(" "); but it gives me the error

':' expected ts(1005) [19,76]

Here is the code snippet:

import  "discord.js";
import { ICommand } from "wokcommands";


export default{

    name: 'nickname',
    category: 'Moderation',
    aliases: ['nick'],
    description: 'Nicks a user',
   
    permissions: ['MANAGE_NICKNAMES'], 

    slash: 'both',
    testonly: true,

    callback: async({ client, message, args}) => {

        const mentionedMember = message? message.mentions.members?.first() : 
        
        const nickName = args.slice(1).join(" "); 
        //gets the nickname

        if (!args[0]) return message.reply('You did not mention a user for me to change their nickname!'); 
        if (!mentionedMember) return message.reply('Please mention a user for me to change their nickname \`>nickname @user nickname\`');
        if (!nickName) return message.reply('Please mention a nickname for me to change this user's nickname');
        //returns an error message if there isn't a user mentioned or the new nick is not specified

        if (!mentionedMember.kickable) return message.reply('This User Has a senior rank than me and I cannot change his nickname') 
        //checks if the user that has been mentioned is below the bot in rank of roles, if not the bot won't be able to change the nickname
        
        await mentionedMember.setNickname(nickName) && await message.reply(`Successfully Changed ${mentionedMember} Nickname to ${nickName}`); 
        //changes the nickname to the specified nickname and sends a message successfully
    
    },

}as ICommand

Answer №1

Are you attempting to use a ternary statement, which is a shorter version of an if-else statement? In a ternary statement, ? represents what should happen when the condition is true, while : represents what should happen when the condition is false. Here's an example:

message = (hasApplesauce) ? 'we have applesauce!' : 'no applesauce :(';

This code snippet will assign "we have applesauce!" to message if hasApplesauce is true, and "no applesauce :(" if hasApplesauce is false. The equivalent conditional code using if-else would look like this:

if (hasApplesauce)
{
    message = 'we have applesauce!';
}
else
{
   message = 'no applesauce :(';
}

You can substitute the boolean with other conditional statements just like you would in any if statement. It seems like the compiler interprets your message? as the start of a ternary statement on the line causing the error, hence why it's asking for a matching :. If you simply want to check if message exists, you should change the line

const mentionedMember = message? message.mentions.members?.first() : 

to

const mentionedMember = message?.mentions.members?.first();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to transfer data received from an observable function to use as an input for another observable function?

After carefully declaring all the variables, I am facing an issue with passing the value obtained from the first observable function (this.acNum) as a parameter to resolve the second observable function within the ngOnInit method. Despite displaying correc ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

Solving the "ExpressionChangedAfterItHasBeenCheckedError" in Ionic: A Guide

//html <span style="margin-left:43%;background-color:rgb(229,229,229);border- radius:10%">&nbsp;&nbsp;{{formatEpoch(epoch)}}&nbsp;&nbsp;</span> //ts lastdate:any; formatEpoch(epoch): string { ...

What is the best way to generate a unique UUID for every object created within a loop?

I am working on a typescript method that eliminates hashtags from a string and saves them in an array within a model. Each element in the hashtag array is assigned a unique UUID along with the complete string added to the model. However, I am facing an iss ...

Method with undefined constructor parameter in Typescript

Understanding how to effectively use Typescript and Angularjs in conjunction has been a challenge for me. Despite reading numerous blog posts and consulting the official documentation for both projects, the concepts just haven't fully clicked. My Ang ...

Guide: Implementing service utilization within a controller using Express and Typescript

This specific piece of TypeScript code is causing me some trouble. I'm attempting to utilize a service to retrieve data from a database, but unfortunately, I keep encountering the following error message: Cannot read property 'populationService&a ...

Hiding the header on a specific route in Angular 6

Attempting to hide the header for only one specific route Imagine having three different routes: route1, route2, and route3. In this scenario, there is a component named app-header. The goal is to make sure that the app-header component is hidden when t ...

How to utilize a defined Bootstrap Modal variable within a Vue 3 single file component

I'm diving into the world of TypeScript and Vue 3 JS. I created a single-file-component and now I'm trying to implement a Bootstrap 5 modal. However, my VSCode is showing an error related to the declared variable type. The error message reads: ...

Using TypeScript without specifying a specific argument in the any type

My function accesses local/session storage, but there is a condition that it can only be called if the window is defined. This function takes a generic args argument which I simplified to have a type of any[]. While using the useSessionStorage function, ...

Running unit tests using Typescript (excluding AngularJs) can be accomplished by incorporating Jasmine and Webpack

While there is an abundance of resources on how to unit test with Webpack and Jasmine for Angular projects, I am working on a project that utilizes 'plain' TypeScript instead of AngularJs. I have TypeScript classes in my project but do not use c ...

In React, the state's value will revert back to its initialState whenever a new value is assigned

My App component has a simple functionality where it controls the state of a value to display a header. By using an onClick function, I'm updating the isHeaderVisible value to True in the Home component when a logo is clicked and another route is take ...

Using React.lazy, Suspense, and react-router-dom for code splitting in React does not function as intended

I'm currently working on setting up a simple example that is similar to the concept of lazy-loading route components as explained here: https://reactjs.org/docs/code-splitting.html#route-based-code-splitting The idea is to dynamically load ModuleOne ...

Inactive function

I have a function that inserts my articles and I call this function on my page. There are no errors, but the next function retrieveAllArticles() is not being executed. public saveAllArticles(article) { for(let data in article) { this.db.exec ...

The canActivate function must be responsive to the true or false value of this.authService.isLoggedIn before proceeding

I am facing a problem with my app's routing functionality. When the user logs in with their Google email, I want the app to route to the home page: "". Everything seems to work fine except for the canActivate routeGuard. During the AuthLogin ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

Vitek - Uncaught ReferenceError: Document Is Not Defined

Why am I encountering an error when trying to use File in my vitest code, even though I can typically use it anywhere else? How can I fix this issue? This is the content of my vite.config.ts. /// <reference types="vitest" /> import { defin ...

Arranging Data in AngularJS based on Selected Filter Criteria

I have a filter function that currently only returns the name values in my table. I would like to add options for both ascending and descending sorting to this filter. Progress So Far: I am able to retrieve values from all inputs, including the name and ...

The specified property is not found in the type 'IntrinsicAttributes & IntrinsicClassAttributes<DatePicker> & Readonly<{ children?: ReactNode; }>'

As I delve into utilizing React along with TypeScript and Material-UI components, I encounter some errors. One such error message pops up like this: The Property 'openToYearSelection' is not found on type 'IntrinsicAttributes & Intr ...

What steps can I take to resolve the "Unable to call a potentially 'undefined' object" error?

I'm currently working with CreateContext in Typescript and I have encountered a problem in the code that I can't seem to resolve. I am trying to use typesafe TX to provide state and dispatch (via useReducer) in a component hierarchy. Here is the ...

Encountering a syntax error when attempting to utilize the colon symbol for specifying data types

Currently, I am a novice who is delving into the world of TypeScript. Here is a snippet of code that I have written: let num: number = 123; console.log(123); However, when attempting to run this file using Node.js and saving it as test.ts, I encounter the ...