What is the solution for the error message "Using a potentially unsafe argument of type 'any' when expecting a parameter of type 'string' in Zod

Interestingly, I am encountering different errors when running the code locally (with zod v3.22.4) compared to on stackblitz using the same version v3.22.4. It seems like both errors may require some fixing.

The stackblitz example, which mirrors the code I have locally, is as follows:

import { z } from 'zod';

type BuildCommandToDecompressWithUnarchiver = {
  overwrite?: boolean;
  password?: string;
  output: {
    directory: {
      path: string;
    };
  };
  input: {
    file: {
      path: string;
    };
  };
};

const BuildCommandToDecompressWithUnarchiverModel: z.ZodType<BuildCommandToDecompressWithUnarchiver> =
  z.object({
    overwrite: z.optional(z.boolean()).default(false),
    password: z.optional(z.string()),
    output: z.object({
      directory: z.object({
        path: z.string(),
      }),
    }),
    input: z.object({
      file: z.object({
        path: z.string(),
      }),
    }),
  });

export function buildCommandToDecompressWithUnarchiver(source) {
  const input = BuildCommandToDecompressWithUnarchiverModel.parse(source);
  const cmd = [
    `unar`,
    `${input.input.file.path}`,
    `-o`,
    `${input.output.directory.path}`,
  ];

  cmd.push('--quiet');

  if (input.overwrite) {
    cmd.push(`-f`);
  }

  if (input.password) {
    cmd.push(`-p`, input.password);
  }

  return cmd;
}

console.log(
  BuildCommandToDecompressWithUnarchiverModel.parse({
    output: {
      directory: {
        path: 'foo',
      },
    },
    input: {
      file: {
        path: 'x.zip',
      },
    },
  })
);

First and foremost, it's worth mentioning that I need

z.ZodType<BuildCommandToDecompressWithUnarchiver>
due to the frequent usage of nested schemas in my definitions. This pattern is essential for successful compilation. Therefore, this structure should remain intact.

However, when testing the code on stackblitz, the error message received is:

Type 'ZodObject<{ overwrite: ZodDefault<ZodOptional<ZodBoolean>>; password: ZodOptional<ZodString>; output: ZodObject<{ directory: ZodObject<{ path: ZodString; }, "strip", ZodTypeAny, { ...; }, { ...; }>; }, "strip", ZodTypeAny, { ...; }, { ...; }>; input: ZodObject<...>; }, "strip", ZodTypeAny, { ...; }, { ...; }>' is not assignable to type 'ZodType<BuildCommandToDecompressWithUnarchiver, ZodTypeDef, BuildCommandToDecompressWithUnarchiver>'.
  The types of '_type.output.directory' are incompatible between these types.
    Type '{ path?: string; }' is not assignable to type '{ path: string; }'.
      Property 'path' is optional in type '{ path?: string; }' but required in type '{ path: string; }'.(2322)

I am uncertain why the error suggests that 'path' is defined as optional when it isn't specified anywhere in the code. Where could this misconception be arising from?

Conversely, when executing the code locally, a distinct error is observed:

Unsafe argument of type `any` assigned to a parameter of type `string`.eslint@typescript-eslint/no-unsafe-argument
(property) password?: string

https://i.sstatic.net/B1QkB.png

This particular "Unsafe argument of type any assigned to a parameter of type string" error recurs in multiple sections across my codebase, all utilizing the same schema definition pattern with zod. Any insights on resolving this issue (and perhaps understanding why stackblitz displays a dissimilar error at times, deviating from the local environment)?

To circumvent the final error, I have resorted to using input.password as string, although this isn't an ideal solution since the data should already be guaranteed as a string by this stage.

Answer №1

It seems like the error occurring on stackbliz is related to a bug in the TypeScript version. To resolve this issue, simply use the keyword as:



const BuildCommandToDecompressWithUnarchiverModel: z.ZodType<BuildCommandToDecompressWithUnarchiver> =
  z.object({
    overwrite: z.optional(z.boolean()).default(false),
    password: z.optional(z.string()),
    output: z.strictObject({
      directory: z.object({
        path: z.string(),
      }).required(),
    }),
    input: z.object({
      file: z.object({
        path: z.string(),
      }).required(),
    }).required(),
  }) as z.ZodType<BuildCommandToDecompressWithUnarchiver>;

Regarding the error code above for local development. This is due to an eslint rule from @typescript-eslint that disallows ambiguous types. You can disable it with:

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument

or

const cmd: string[] = [
  // ...
]

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

common problems during initial setup of AngularJS 2

My background is in PHP and JavaScript, and I have limited experience with nodejs and angular js. While attempting to learn angular js 2, I encountered difficulties setting up my first example. I am using node v 5.6.0 and npm version 3.7.2 on ubuntu 14. ...

Enhancing TypeScript Native Interface Properties in TypeScript 2.4

After discovering an error in the native Typescript interface for HTMLTextAreaElement, I realized the need to make a correction. The current interface looks like this: interface HTMLTextAreaElement { setSelectionRange(start: number, end: number): void; ...

What is the best way to display multiple HTML files using React?

Looking to develop a web application using React that consists of multiple HTML pages. For instance, login.html and index.html have been created and linked to URIs through the backend - resulting in localhost:8080/login and localhost:8080/index. However, R ...

Enhance your map by incorporating an overlay with ngx-openlayers

Currently, I am trying to implement zoom-in and zoom-out buttons on an OpenLayers map. I attempted to use the overlay method but encountered an error. Here is the code snippet for reference: zoom_button = document.getElementById('zoom') zo ...

Is the form considered dirty after updating the form value using the patchValue method?

Exploring the concept of the patchValue method, I discovered that when using this method to update form values, the form is marked as dirty. // Implementing it like this setTimeout(() => { this.skillForm.patchValue({ date: [new Date()] ...

Facing problem with Angular 7 when making a GET request for non-JSON data

Currently, I am retrieving JSON data from a URL using the following method: this.http.get('http://localhost:3200/mydata').subscribe(data => { console.log(data); }); The response is in JSON format, and everything seems to be working fine. ...

Is it possible to utilize the Angular selector twice while only initializing the component once?

HTML <exchange></exchange> <exchange></exchange> TS @Component({ selector: 'exchange', templateUrl: 'exchange.component.html', }) export class ExchangeCompone ...

Show the key names of a React object

Check out my demonstration here This React TypeScript application showcases the display of an object The structure of the object is as follows: { "default": { "ProductSize": { "min": 32 }, ...

Can optional parameters be used to restrict TypeScript overloads in any way?

My objective is as follows: interface ColorRgb { red: number; green: number; blue: number; } function rgbToHex(red: ColorRgb, green?: undefined, blue?: undefined): string function rgbToHex(red: number, green: number, blue: number): string function r ...

Getting an error in React when using Typescript with a functional component? The issue might be that you are trying to assign a type 'boolean' to a type 'ReactElement<any, any>'

Recently, I set up a project that utilizes TypeScript in conjunction with React. As part of the project, I created a Layout component that relies on the children prop. Below is the current code snippet: import React from 'react'; type LayoutProp ...

What could be causing the rendering issue on this React component page when an id is provided in the React Router URL?

These are the dependencies I am using for my React project: "react": "^16.13.1", "react-dom": "^16.13.1", "react-helmet": "^6.1.0", "react-html-parser": "^2.0.2", "react-i ...

Despite the availability of data, the payload in redux remains consistently undefined

I am facing an issue with my Next.js application that uses redux/redux saga. When data is received from the backend (verified in the browser's network tab), it is being sent to the reducer as undefined. I initially thought it could be due to the paylo ...

What is the best way to programmatically click on an element within the body of a webpage from an Angular component?

I am running a crisp chat service on my website and I am attempting to interact with the chat box from one of my component's typescript files. The chat box is represented as a div element with the id crisp-client inside the body tag. Can someone plea ...

Is it possible to provide unrestricted support for an infinite number of parameters in the typing of the extend function from Lodash

I am utilizing the "extend" function from lodash to combine the objects in the arguments as follows: import { extend } from 'lodash'; const foo1 = { item: 1 }; const foo2 = { item: 1 }; const foo3 = { item: 1 }; const foo4 = { item: 1 }; const f ...

What is the best way to create a dynamic icon using React and TypeScript?

Excuse me, I am new to using React and TypeScript. I'm having trouble getting the icon to change based on the status in AppointmentType. The body color is working fine, but the icons are not changing. Can someone please help me solve this issue? const ...

Tips for categorizing the properties of an object based on their types

interface initialStateInterface { user: object; age: number; } const initialState = { user: { username: "", email: "" }, age: 0, }; In this code snippet, I have defined an interface type for the initial state containing a user ...

Enzyme: utilizing shallow rendering for a component that necessitates an extremely precise child type

Picture having these two elements class Mother ... { render() { let baby; if(this.props.children[0].type.IS_CHILD){ this.props.children[0].isInsideMother = true; baby = this.props.children[0]; ...

The initial function is executed only after the second function has completed, as it relies on the

For a small project of mine, I've been attempting to load JSON data. However, the issue arises when the loadDefs function is executed before checking if file_data has been modified. loadDefs(file_path:any) { let file_data:string = '&a ...

Is it possible for me to assign a general data type to a function that duplicates an item while adding or changing a key with a different value?

In my recent coding endeavor, I've crafted the following function: function extend(obj, key, value) { return { ...obj, [key]: value } } Ideally, I want to utilize this function in a versatile manner, with obj representing an Object of which the t ...

Create a simulated constructor to generate an error

Currently, I am faced with a challenge of writing a test that is expected to fail when trying to instantiate the S3Client object. It seems like Vitest (similar to Jest) replaces the constructor with its own version when mocked, preventing my original const ...