I would like recommendations on the full range of potential attributes that an object can have in TypeScript

I am facing an issue with understanding the different message properties in Telegraf (4.6.0) types.

This is what I currently have:

import { Telegraf, Context } from 'telegraf'

const myBot = new Telegraf(myToken)
listenerBot.on('message', (ctx: Context) => {
    const {
        text,
        forward_from_chat, forward_from_message_id,
        photo, caption, caption_entities,
        // unsure about properties for video, audio, document, etc.
    } = ctx.message as any
    // perform actions with the message
}

Due to messages being of various types, when I type ctx.message. in my IDE (specifically VS Code), only suggested props that are always present in the message object like message_id appear. Although I can check using conditions like

if('text' in ctx.message) {
    // do something with ctx.message.text
}

this approach does not help me discover all possible props that ctx.message may contain. One potential method could be

class ExploredContext = ExploreProps<Context> → provides a class resembling Context where 
  all potential props are non-optional

...
(ctx as ExploredContext).message._ // cursor here, IDE displays available props
(ctx.message as ExploredMessage)._ // or similar

However, I am uncertain how to create a helper like ExploreProps since I am only familiar with utility types. Additionally, I am unaware of any cleaner alternatives to achieve this goal without resorting to hacky methods involving TypeScript configurations and/or IDE settings.

Can you recommend a technique for implementing ExploreProps or a more efficient way to explore potential props?

(I also inquired about this in a Telegraf issue, but a universal solution would be beneficial regardless of Telegraf)

Answer №1

To compress a combination, utilize StrictUnion as outlined here. This specification will essentially fill in the absent elements for all constituents of the combination with the kind undefined. This enables destructuring to propose all elements from any constituent, although each element not found in every constituent of the combination will also include undefined (which is likely preferable for type safety reasons).

import { Example1, Example2 } from 'example'

type UnionAttributes<T> = T extends T ? keyof T : never;
type CompleteUnionHelper<T, TAll> = T extends any ? T & Partial<Record<Exclude<UnionAttributes<TAll>, keyof T>, undefined>> : never;
type CompleteUnion<T> = CompleteUnionHelper<T, T>

const myToken = ""
const myExample = new Example1(myToken)
myExample.on('event', (ctx: Context) => {
    const {
        desc,
        origin_chat, orig_msg_id,
        image, caption, cap_entities,
        
    } = ctx.message as CompleteUnion<Context['message']>
})

Playground Link

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 send file data as a response from an express route in NodeJS?

I have a local JSON file structured as follows: { license: "abcd", name: "abcd", data: [ Array of JSON Objects .... ] } I am attempting to access the data array within the object and send it as a response from an Exp ...

Extract values from a deeply nested object while retaining the type information

How can I map all object values of the first obj while preserving the generic type for the Wrapped object? I attempted this using a mapped type, but encountered two issues: I'm struggling to represent a nested Object in the MapToWrappedType I can&ap ...

Extend the row of the table according to the drop-down menu choice

I am working on a feature where a dropdown menu controls the expansion of rows in a table. Depending on the option selected from the dropdown, different levels of items need to be displayed in the table. For example, selecting level 1 will expand the first ...

Dismiss the Popover in Ionic 2

After opening a popover that redirects me to another page and then returning to the root page (popToRoot), I reload the data/dom upon an event and dismiss the popup once the json data is received from the server. Everything works smoothly with a lengthy ti ...

The Hapi response fails to display JSON data in a nested tree format

Hey there! I've got this object with a specific structure. Here it is: interface FolderWithContent { uuid: string name: string; folders: Array<FolderWithContent>; files: Array<Files>; } Just a heads up, Files is an extens ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

Developing interconnected dropdowns in Angular 8 for input fields

Imagine we have a list of names structured like this: nameSelected: string; names: Name[ {firstName: 'John', middleName: 'Danny', lastName: 'Smith'}, {firstName: 'Bob', middleName: 'Chris', lastN ...

Why does the ReactJS MaterialUI Modal fail to update properly?

Recently, I encountered a curious issue with my Modal component: https://i.stack.imgur.com/dkj4Q.png When I open the dropdown and select a field, it updates the state of the Object but fails to render it in the UI. Strangely, if I perform the same action ...

Angular gives priority to input when clicking an element

Please find the stackblitz link attached below. https://stackblitz.com/edit/angular-dgx3pe My goal is to achieve a functionality where clicking on the label element will focus on the input. This should trigger the input:focus class. I believe this can be ...

An issue occurred while attempting to retrieve information from the database table

'// Encounter: Unable to retrieve data from the table. // My Code const sql = require('mssql/msnodesqlv8'); const poolPromise = new sql.ConnectionPool({ driver: 'msnodesqlv8', server: "test.database.windows.net", ...

Having trouble with the rowNode functionality in PrimeNG TreeTable

I am currently utilizing the PrimeNG Treetable component from https://www.primefaces.org/primeng/#/treetable I seem to be encountering issues with retrieving data from the service. Below is a snippet of my code: HTML <p-treeTable [value]="temp"> & ...

Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when ...

Decoding the HTML5 <video> tag using the html-react-parser library

I'm working on a NextJS V13 app where I need to display HTML content fetched from a CMS. Instead of using dangerouslySetHtml, I opted for the html-react-parser package to parse the HTML and replace certain embedded tags like <a>, <img>, an ...

IntelliSense in VS Code is unable to recognize CSS files

I'm currently in the process of creating a React application, however, I've encountered an issue where importing a .css file doesn't prompt vscode to display the file in the intellisense feature. https://i.sstatic.net/nxhyV.png It's u ...

Form validation errors were detected

Currently, I am working with a formgroup that contains input fields with validations set up in the following manner: <mat-form-field class="mat-width-98" appearance="outline"> <mat-label>Profession Oc ...

What could be the root cause behind the error encountered while trying to authenticate a JWT?

I've been working on integrating a Google OAuth login feature. Once the user successfully logs in with their Google account, a JWT token is sent to this endpoint on my Express server, where it is then decoded using jsonwebtoken: app.post('/login/ ...

What steps are needed to generate an RSS feed from an Angular application?

I have a website built with Angular (version 12) using the Angular CLI, and I am looking to generate an RSS feed. Instead of serving HTML content, I want the application to output RSS XML for a specific route like /rss. While I plan on utilizing the rss p ...

having difficulty accessing the value within the Angular constructor

My current issue arises when I click on a button and set a value within the button click method. Despite declaring the variable in the constructor, I am unable to retrieve that value. The code snippet below demonstrates this problem as I keep getting &apos ...