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

Convert the date into a string format instead of a UTC string representation

I am currently working on a node.js project using TypeScript. In this project, I have a Slot class defined as follows: export class Slot { startTime: Date; constructor(_startTime: Date){ this.startTime = _startTime } } // Within a controller method ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

Having trouble utilizing the Visual Studio Code debugger in an Express.js project that uses TypeScript

My package.json file is shown below: ` { "name": "crm-backend", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev" ...

Angular Error: The first argument has a property that contains NaN

Struggling with a calculation formula to find the percentage using Angular and Typescript with Angularfire for database storage. Encountered an error stating First argument contains NaN in property 'percent.percentKey.percentMale. The properties are d ...

The guidelines specified in the root `.eslintrc.json` file of an NX workspace do not carry over to the project-level `.eslintrc.json` file

In my main .eslintrc.json file, I have set up some rules. This file contains: { "root": true, "ignorePatterns": ["**/*"], "plugins": ["@nrwl/nx", "react", "@typescript-eslint", &qu ...

Creating an Angular form from scratch using HTML

I've developed a component named login. Initially, I created an HTML form called login.component.html and then decided to convert it into an Angular form. To achieve this, I inserted <form #loginform="ngForm"> in the login.component.ht ...

Customizing the output format of Ng Date Picker beyond the standard ISO-8601

Just to clarify, I'm talking about a specific DatePicker component that can be found at the following link: Although the DatePicker interface is user-friendly and visually appealing, I'm facing an issue with the way it outputs values. While ther ...

The return type in Typescript is populated with a generic type name that lacks meaningful

When utilizing ts-results-es, I encounter an issue. This library aids in wrapping errors within a class to provide insight into potential function errors. Here is a simplified class definition: interface BaseResult<T, E> {} class Err<E> imple ...

When trying to access the DOM from another module in nwjs, it appears to be empty

When working with modules in my nwjs application that utilize document, it appears that they are unable to access the DOM of the main page correctly. Below is a simple test demonstrating this issue. The following files are involved: package.json ... "ma ...

To work on React with typescript, your Type must include a method '[Symbol.iterator]()' that will fetch an iterator

Here is a demonstration I have prepared for you: https://stackblitz.com/edit/react-ts-shopping-cart-ssofgc?file=Shop.tsx Apologies for the lack of clarity in my question, but... The demo I created showcases a basic shopping cart using React and Typescri ...

Strange occurrences with HTML image tags

I am facing an issue with my React project where I am using icons inside img tags. The icons appear too big, so I tried adjusting their width, but this is affecting the width of other elements as well. Here are some screenshots to illustrate: The icon wit ...

ReactJS: A single digit input may result in the display of numerous '0's

My goal is to have a small box that only allows one digit, but it seems to work fine until I try to input multiple '0's. Then the box displays multiple 0000 persistently. Here is the code snippet: const InputBox = () => { const [value, ...

Observing fluctuations in variable values within Angular2

How can I track changes in a variable bound to an input type text? I attempted using Observables, but the change event is not being triggered. Does anyone have an example or documentation on this? ...

Create a tuple type by mapping an object with generics

I have a specified object: config: { someKey: someString } My goal is to generate a tuple type based on that configuration. Here is an example: function createRouter< T extends Record<string, string> >(config: T) { type Router = { // ...

Issue with Angular 2 Routing: Unable to find a matching route

Currently, I'm in the process of developing an Angular 2+ application that requires routing. One of the requirements is for the color scheme of the entire app to change based on a URL parameter input. In my app.module.ts file, I have the following co ...

Leveraging default values in generic implementations

Imagine a scenario where the following code is present: type QueryResult<ResultType = string, ErrorType = string> = { result: ResultType, } | { errors: ErrorType, } So, if I want to initialize my result, I can proceed like this: const myResult: ...

Using jscodeshift, transform all named import statements to default import statements for MUI V5

I'm in need of assistance with a jscodeshift script to convert all named imports to default imports for Material-UI version 5 using React and Typescript. import { Button, TextField } from '@mui/material'; The desired result should be: impor ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...

Making an Angular POST request and then navigating to a new component

Hello, I am a beginner in Angular and struggling to make my code work. It seems like a basic functionality issue that I can't seem to figure out. My goal is to send a post request to my .NET core API to register a user, and once that is done, navigat ...

Understanding the fundamentals of TypeScript annotation and node package management

As a newcomer to Typescript, I have grasped the basics but find myself becoming a bit bewildered when it comes to best practices for handling node packages, annotations, and defining types within those packages in my projects. Do I really need to annotate ...