Extending an External Object with Custom Properties in TypeScript

When working with an external library, I often find myself needing to add new properties to passed-in parameters. Instead of using (<any>conv.data) due to the compiler error Object is of type 'unknown', I'm curious if there's a more effective approach for achieving this.

Any suggestions on how to improve this process?

import { dialogflow, Permission } from 'actions-on-google';

const app = dialogflow({ debug: true });

app.intent('actions_intent_PERMISSION', (conv, _, permissionGranted) => {
  if (!permissionGranted) {
    conv.ask('Bye Bye!')
  } else {
    (<any>conv.data).userName = conv.user.name.display
    conv.ask(`Thanks, ${(<any>conv.data).userName}.`)
  }
})

Answer №1

It seems like there is type information available for conv, but the data attribute is missing. It's important to define data in some way; if not, it would be best to update the type information to include data. You could consider defining data as any, although specifying its properties (optional ones can be marked as optional) would be more beneficial. Alternatively, you could define it as [key: string]: any, but this may not offer much advantage over just using any.

If there is no type information available for conv, you have the option to define it yourself. Here is an example:

interface Conv {
    ask(msg: string): void;
    data: {[key: string]: any};
    user: {
        name: {
            display: appropriateTypeHere;
       }
    }
}

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 process for marking a form field as invalid?

Is it possible to validate the length of a field after removing its mask using text-mask from here? The problem is that the property "minLength" doesn't work with the mask. How can I mark this form field as invalid if it fails my custom validation met ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

Using the <head> or <script> tag within my custom AngularJS2 component in ng2

When I first initiate index.html in AngularJS2, the structure looks something like this: <!doctype html> <html> <head> <title>demo</title> <meta name="viewport" content="width=device-width, initial-scal ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Utilizing trackingjs as an external library in Ionic2

I have been attempting to incorporate the trackingjs library (https://www.npmjs.com/package/tracking) into my ionic2 project. Following the guidelines in the documentation (https://ionicframework.com/docs/v2/resources/third-party-libs/), I was able to suc ...

Encountered difficulty retrieving properties from the req.query object within expressjs

My setup includes a router configuration like this: router.get('/top-5-cheap', aliasTopTours, getAllTours); I've also implemented some middlewares: Middleware aliasTopTours: In this middleware, I am setting certain properties on the reque ...

The initial click may not gather all the information, but the subsequent click will capture all necessary data

Issue with button logging on second click instead of first, skipping object iteration function. I attempted using promises and async await on functions to solve this issue, but without success. // Button Code const btn = document.querySelector("button") ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Observable - initiating conditional emission

How can I make sure that values are emitted conditionally from an observable? Specifically, in my scenario, subscribers of the .asObservable() function should only receive a value after the CurrentUser has been initialized. export class CurrentUser { ...

Ways to manage drag and drop functionality within Cypress when traditional Cypress techniques are not effective

I need help with the drag and drop function in Cypress. I have tried three different methods but none of them seem to work. I have included my code below, which is not functioning as expected. Does anyone have any suggestions on what might work better in t ...

Acquire the URL using Angular within a local environment

I am currently working on a basic Angular project where I have a JSON file containing some data. [{ "name": "Little Collins", "area": "Bronx", "city": "New York", "coverImage": "https://images.unsplash.com/photo-1576808597967-93bd9aaa6bae?ixlib=rb-1.2.1&a ...

Want to enhance user experience? Simply click on the chart in MUI X charts BarChart to retrieve data effortlessly!

I'm working with a data graph and looking for a way to retrieve the value of a specific column whenever I click on it, and then display that value on the console screen. Check out my Data Graph here I am using MUI X charts BarChart for this project. ...

Typescript's ability to have Enums with dynamic keys

Suppose I define: enum Sort { nameAsc = 'nameAsc', nameDesc = 'nameDesc' } Is it possible to do the following? const key = 'name' + 'Desc'; Sort[key] Appreciate any help in advance ...

Adding a value to an array in TypeScript

When trying to add values to an array in my code, I encountered an error stating that "number" is not a valid type for the array. someArray: Array <{ m: number, d: Date}> = []; this.someArray.push(500,new Date(2020,1,15)); ...

React Typescript - Unexpected character ',' encountered at line 1005

Currently, I am utilizing Typescript within a React application that integrates with Graphql. Encountering an error: ',' expected.ts(1005) After researching possible solutions, most suggest that the issue might be due to using an outdated ve ...

Resolving type error issues related to using refs in a React hook

I have implemented a custom hook called useFadeIn import { useRef, useEffect } from 'react'; export const useFadeIn = (delay = 0) => { const elementRef = useRef<HTMLElement>(null); useEffect(() => { if (!elementRef.current) ...

React Hot Toast useState is unfortunately not exported from the React library

While working on a Next.js project, I encountered an issue when trying to use react-hot-toast. When I attempted to import it into any file, I received the following error message: Error - ./node_modules/react-hot-toast/dist/index.mjs Attempted import erro ...

How to set the type of an object property to a string based on a string from an array of strings in TypeScript

Great { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Alice', } Not So Good { choices: ['Bob', 'Chris', 'Alice'], selectedChoice: 'Sam', } I've been exp ...

I encountered a problem while integrating antd and moment.js in my React project

I am currently using the antd date-picker in my React project with TypeScript. Encountered an error: Uncaught Type Error: moment is not a function. If anyone has a solution, please assist me. .tsx file:: const dateFormat = 'MM-DD-YYYY'; < ...

Creating a global variable in Angular that can be accessed by multiple components is a useful technique

Is there a way to create a global boolean variable that can be used across multiple components without using a service? I also need to ensure that any changes made to the variable in one component are reflected in all other components. How can this be ac ...