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

The specified type 'MutableRefObject<HTMLInputElement | undefined>' cannot be assigned to type 'LegacyRef<HTMLInputElement> | undefined'

Consider the following simplified component : const InputElement => React.forwardRef((props:any, ref) => { const handleRef = React.useRef<HTMLInputElement|undefined>() React.useImperativeHandle(ref, () => ({ setChecked(checke ...

Having trouble executing the project using Gulp

I'm a beginner in front-end development and I am working on an existing project that I'm having trouble running. According to the documentation, I should run the project by executing: $ gulp && gulp serve But I keep getting this error: ...

Steps for utilizing an `<a>` link tag to submit a form in Angular 4

Is there a way to retrieve the selected option in this form from the other side when clicking a link? <form (ngSubmit)="onSubmit(x)"> <input type="radio" id="radioset3" name="radioset" [checked]="x==0"> <input type="radio" id="radio ...

Is it possible that a declaration file for module 'material-ui/styles/MuiThemeProvider' is missing?

I have been trying to implement the react material-ui theme after installing it via npm. However, I am encountering errors when adding 'import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";' in boot-client.tsx: TS7016: Could not ...

Why does tsc produce a compiled file that throws an exception when executed, while ts-node successfully runs the TypeScript file without any issues?

I have written two ts files to test a decorator. Here is the content of index.ts: import { lockMethod } from './dec'; class Person { walk() { console.info(`I am walking`); } @lockMethod run() { console.info(`I am running`); } ...

Timestamps are no longer recognized in Highstock charts once data has been added

In my highstock chart, I am pulling data from a REST api and everything appears correct. However, there is no data available between 19:00 and 05:00. I would like this absence of data to be reflected in the chart without cropping out that time span from th ...

How can I dynamically render a component using VueJS?

Incorporating a component named CanvasComp from my components folder, I am rendering it on the template like <CanvasComp :jsoData="data"/> to send jsonData to the component. However, I am seeking a way to dynamically render this component w ...

Error TS2488 in React TypeScript: The data type 'IStateTypes' is required to have a method called '[Symbol.iterator]()' that returns an iterator

At the moment, I am working on implementing a global state in React Hooks but have run into an issue. https://i.stack.imgur.com/DN83K.png The current problem I'm facing is with [Symbol.iterator](. I am uncertain about how to resolve this as I am in ...

Type ' ' cannot be assigned to type ''..ts(2322) ANOTHA ONE

Being a beginner in TypeScript and currently learning about enums, I encountered an error with the following example code that I cannot seem to understand. Here's the code snippet: enum Status { SUCCESS = 'success', FAILED = 'fa ...

I encounter an error in my JavaScript function indicating that it is not defined

let element = document.querySelector("#value"); let buttons = document.querySelectorAll(".btn"); buttons.forEach(function (button) { button.addEventListener("click", function(event){ console.log(event.currentTarge ...

Navigating through different components within a single page

Each segment of my webpage is a distinct component, arranged consecutively while scrolling e.g.: <sectionA></sectionA> <sectionB></sectionB> <sectionC></sectionC> All the examples I've come across involve creating ...

Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilit ...

Downloading PDF files on IOS while using Angular often results in the PDF opening in the same

I'm currently utilizing file-saver within my Angular application to retrieve a PDF generated from the backend. The library functions smoothly on desktop and Android devices, but I'm encountering issues with downloading files on iOS. Contrary to w ...

Encountering the "RequestDevice() chooser has been cancelled by the user" error when using Electron 17.x with Web Bluetooth

After reviewing the following StackOverflow resources: Web Bluetooth & Chrome Extension: User cancelled the requestDevice() chooser Electron Web Bluetooth API requestDevice() Error Can you manipulate web bluetooth chooser that shows after calling requestD ...

Encountering an issue while upgrading to Angular 10: Unable to interpret "tsconfig.json" as a valid JSON AST Object

I'm currently updating my Angular 9 app to Angular 10 and encountering this error: > Removing "Solution Style" TypeScript configuration file support. × Migration failed: Failed to parse "tsconfig.json" as JSON AST Object. PropertyNameExpected at l ...

Setting up Jest to run in WebStorm for a Vue project with TypeScript can be done through

I am struggling to run all my tests within WebStorm. I set up a project with Babel, TypeScript, and Vue using vue-cli 3.0.0-rc3. My run configuration looks like this: https://i.stack.imgur.com/7H0x3.png Unfortunately, I encountered the following error: ...

Having trouble linking the date object with the default value of the date input field

Exploring how to set the default value of a date type input using property binding. Initially, I attempted to create a new date object in app.component.ts and then bind the [value] attribute of the date input to the currentDate property within app.compone ...

Efficiently managing repeated records in NodeJS using loops

I am trying to retrieve sales records for specific products from a table in my database based on client ID. This is how I attempted to achieve it: public async getData(clientID: any): Promise<any> { try { return await client .scan( ...

Having trouble with Typescript subtraction yielding unexpected results?

If I have a total amount including VAT and want to separate the net price and the VAT value, how can this be done? For example, if the final price is $80.60 with a VAT rate of 24%, what would be the net price and the VAT value? The correct answer should ...

Creating a Route in Angular 2 for a Component other than the one initialized with the bootstrap function

I am currently in the process of working on a project involving Angular2. If you are interested in understanding why I need to do what I am about to explain, please take a look at this issue. The main component in my project is called AppComponent and it ...