Combining declarations to ensure non-null assets

Let's modify this from @types/aws-lambda to clearly indicate that our intention is for pathParameters to not be null and have a specific format.

export interface APIGatewayProxyEventBase<TAuthorizerContext> {
    body: string | null;
    headers: APIGatewayProxyEventHeaders;
    multiValueHeaders: APIGatewayProxyEventMultiValueHeaders;
    httpMethod: string;
    isBase64Encoded: boolean;
    path: string;
    pathParameters: APIGatewayProxyEventPathParameters | null;
    // ...snip...
}
export interface APIGatewayProxyEventPathParameters {
    [name: string]: string | undefined;
}

In our codebase, we can specify that fooId is not null

declare module "aws-lambda/trigger/api-gateway-proxy" {
  export interface APIGatewayProxyEventPathParameters {
    fooId: string;
  }
}

export const handler: APIGatewayProxyHandler = async (event) => {
  // This check is still necessary
  if (!event.pathParameters) {
    throw new Error("parameter is empty");
  }
  // Without declaration merging, fooId could be string or undefined,
  // but now it's just a string
  const { fooId } = event.pathParameters;

To get rid of the need for if (!event.pathParameters), I tried this:

declare module "aws-lambda/trigger/api-gateway-proxy" {
  export interface APIGatewayProxyEventBase<T> {
    pathParameters: APIGatewayProxyEventPathParameters;
  }
  export interface APIGatewayProxyEventPathParameters {
    fooId: string
  }
}

We encountered the following error as a result:

error TS2428: All declarations of 'APIGatewayProxyEventBase' must have identical type parameters.
error TS2717: Subsequent property declarations must have the same type.  Property 'pathParameters' must be of type 'APIGatewayProxyEventPathParameters | null', but here has type 'APIGatewayProxyEventPathParameters'.

Is it possible for event to be of type

{ pathParameters: { fooId: string }, ... }
instead of
{ pathParameters?: { fooId: string }, ... }
?

Answer №1

If you want to achieve this, you can utilize the Omit utility type.

interface ModifiedEvent extends Omit<APIGatewayProxyEventV2, 'pathParameters'> {
  pathParameters: { fooId: string }
}

After that, make sure to specify the event argument in your handler with the updated ModifiedEvent type.

export const handler: Handler<ModifiedEvent, APIGatewayProxyResultV2> = (event) => { ... }

You can find more details and examples related to handler types in this document.

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 attribute 'finally' is not found on the data type 'Promise<void>'

I've been attempting to implement the finally method on a promise but continue running into this issue. Property 'finally' does not exist on type 'Promise<void>'. After researching similar problems, I found suggestions to a ...

Incorporating interactive buttons within Leaflet popups

I'm facing an issue with adding buttons to a Leaflet popup that appears when clicking on the map. My goal is to have the popup display 2 buttons: Start from Here Go to this Location The desired outcome looks like this sketch: ___________________ ...

Setting up Next Js to display images from external domains

Encountering an issue with my next.config.js file while working on a project with Next.js in TypeScript. This project involves using ThreeJs, @react-three/fiber, and @react-three/drei libraries. Additionally, I need to include images from a specific public ...

Creating a personalized event using typescript

I need help with properly defining the schema for an EventObject, specifically what should be included within the "extendedProps" key. Currently, my schema looks like this: interface ICustomExtendedProps { privateNote?: string; publicNote?: string; ...

Having trouble accessing store state in Angular with NGXS

In the parent component, I am dispatching an action and hoping to receive the dispatched array in the child component. To achieve this, I have implemented the following code: export class ListComponent implements OnInit { @Select(ProductState.getProductD ...

Handling mouse events with Angular 2 (tracking movement based on current position)

One of the features I want to implement for my user is the ability to move or rotate an object in a canvas using the mouse. The process involves calculating the delta (direction and length) between successive mouse events in order to update the position of ...

The use of 'import ... =' is restricted to TypeScript files

Error: Oops! Looks like there's a hiccup in the code... 'import ... =' is exclusive to TypeScript files. Expecting '=' here. Don't forget the ';'. Unexpected keyword or identifier popping up! package.json ...

The `Required<Partial<Inner>>` does not inherit from `Inner`

I stumbled upon a code snippet that looks like this: type Inner = { a: string } type Foo<I extends Inner> = { f: I } interface Bar<I extends Inner> { b: I } type O<I extends Partial<Inner>> = Foo<Required<I>> & B ...

Step-by-step guide for setting up automatic Tslint in IntelliJ

When working on an Angular project in Intellij, I often encounter numerous tslint errors while coding. Is there a command within Intellij that can automatically fix all of these lint errors? ...

How will the presence of @types/react impact the higher-level files in my project?

Here is the structure of my directories vue node_modules src react_app node_modules @types/react package.json ...other file package.json Why does the presence of "@types" in a subdirectory affect the top-level directory? I ...

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 ...

What could be the reason for encountering a Typescript ts(2345) error while trying to pass a mocked constant to .mockResolvedValue()?

Within my test.tsx file, I have the following code snippet: test('Photos will load', async () => { const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos'); mockCuratedPhotos.mockResolvedValue(mockPhotos); awa ...

Enhancing the TypeScript typings of modules in Angular 2

In my Angular2 application, I am facing an issue with an external NPM package that has an outdated typings file. This means there are functions within the package that are present but not declared in the typings file. My main goals are: To create and ut ...

Limit an object to only contain interface properties

Suppose we have the following object: o {a : 1, b : 2} and this interface defined as: interface MyInterface { a : number } We are now looking to create a new object that represents the "intersection" of o and the MyInterface: o2 : {a : 1} The mai ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

What methods can I utilize from Google Maps within Vuex's createStore()?

Currently, I am in the process of configuring my Vuex store to hold an array of Marker objects from the Google Maps Javascript API. Here is a snippet of how my createStore function appears: import { createStore } from "vuex"; export default ...

Unveiling the mysteries of abstract classes in TypeScript

I have a collection of different animal classes, all derived from a common abstract base class. To illustrate: abstract class Animal { abstract speak(): string; } class Dog extends Animal { speak(): string { return "woof... sigh" } } ...

Error encountered when attempting to pass i18next instance to I18nextProvider

Issue: Error message: Type 'Promise' is missing certain properties from type 'i18n': t, init, loadResources, use, and more.ts(2740) index.d.ts(344, 3): The expected type is derived from the property 'i18n' declared within ty ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...

Ways to retrieve form data from a dynamic CDKPortalComponent

I have a dynamic cdkportal component that is created from a variety of Components. These components are added to a modal dialog, and I need to determine the validity of the forms within them. If any of the child component forms are invalid, I want to disab ...