Búsqueda de sitios web

reactjs - Error de compilación de Next.js TypeScript: Problema con el tipo 'OmitWithTag'


`Entonces tengo un proyecto en Next Js y uso TypeScript. Intenté construir mi proyecto usando npm run build y después la terminal dice esto:`

Type 'OmitWithTag<InputFormProps, keyof PageProps, "default">' does not satisfy the constraint '{ [x: string]: never; }'.
Property 'type' is incompatible with index signature.
Type 'string' is not assignable to type 'never'.

26 |
27 | // Check the prop type of the entry function
28 | checkFields<Diff<PageProps, FirstArg<TEntry['default']>, 'default'>>()
     |             ^
29 |
30 | // Check the arguments and return type of the generateMetadata function
31 | if ('generateMetadata' in entry) {

Encontré un archivo donde apareció mi error y está ubicado en la carpeta .next, que no cambié ni toqué, se creó automáticamente durante la compilación. Aquí está el código para ello:

     // File: C:\Users\igovt\OneDrive\Desktop\MeetUps\meet-ups\meetups\app\components\InputForm\page.tsx
import * as entry from '../../../../../app/components/InputForm/page.js'
import type { ResolvingMetadata, ResolvingViewport } from 'next/dist/lib/metadata/types/metadata-interface.js'

type TEntry = typeof import('../../../../../app/components/InputForm/page.js')

// Check that the entry is a valid entry
checkFields<Diff<{
  default: Function
  config?: {}
  generateStaticParams?: Function
  revalidate?: RevalidateRange<TEntry> | false
  dynamic?: 'auto' | 'force-dynamic' | 'error' | 'force-static'
  dynamicParams?: boolean
  fetchCache?: 'auto' | 'force-no-store' | 'only-no-store' | 'default-no-store' | 'default-cache' | 'only-cache' | 'force-cache'
  preferredRegion?: 'auto' | 'global' | 'home' | string | string[]
  runtime?: 'nodejs' | 'experimental-edge' | 'edge'
  maxDuration?: number
  
  metadata?: any
  generateMetadata?: Function
  viewport?: any
  generateViewport?: Function
  
}, TEntry, ''>>()

// Check the prop type of the entry function
checkFields<Diff<PageProps, FirstArg<TEntry['default']>, 'default'>>()

// Check the arguments and return type of the generateMetadata function
if ('generateMetadata' in entry) {
  checkFields<Diff<PageProps, FirstArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>()
  checkFields<Diff<ResolvingMetadata, SecondArg<MaybeField<TEntry, 'generateMetadata'>>, 'generateMetadata'>>()
}

// Check the arguments and return type of the generateViewport function
if ('generateViewport' in entry) {
  checkFields<Diff<PageProps, FirstArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>()
  checkFields<Diff<ResolvingViewport, SecondArg<MaybeField<TEntry, 'generateViewport'>>, 'generateViewport'>>()
}

// Check the arguments and return type of the generateStaticParams function
if ('generateStaticParams' in entry) {
  checkFields<Diff<{ params: PageParams }, FirstArg<MaybeField<TEntry, 'generateStaticParams'>>, 'generateStaticParams'>>()
  checkFields<Diff<{ __tag__: 'generateStaticParams', __return_type__: any[] | Promise<any[]> }, { __tag__: 'generateStaticParams', __return_type__: ReturnType<MaybeField<TEntry, 'generateStaticParams'>> }>>()
}

type PageParams = any
export interface PageProps {
  params?: any
  searchParams?: any
}
export interface LayoutProps {
  children?: React.ReactNode

  params?: any
}

// =============
// Utility types
type RevalidateRange<T> = T extends { revalidate: any } ? NonNegative<T['revalidate']> : never

// If T is unknown or any, it will be an empty {} type. Otherwise, it will be the same as Omit<T, keyof Base>.
type OmitWithTag<T, K extends keyof any, _M> = Omit<T, K>
type Diff<Base, T extends Base, Message extends string = ''> = 0 extends (1 & T) ? {} : OmitWithTag<T, keyof Base, Message>

type FirstArg<T extends Function> = T extends (...args: [infer T, any]) => any ? unknown extends T ? any : T : never
type SecondArg<T extends Function> = T extends (...args: [any, infer T]) => any ? unknown extends T ? any : T : never
type MaybeField<T, K extends string> = T extends { [k in K]: infer G } ? G extends Function ? G : never : never



function checkFields<_ extends { [k in keyof any]: never }>() {}

// https://github.com/sindresorhus/type-fest
type Numeric = number | bigint
type Zero = 0 | 0n
type Negative<T extends Numeric> = T extends Zero ? never : `${T}` extends `-${string}` ? T : never
type NonNegative<T extends Numeric> = T extends Zero ? T : Negative<T> extends never ? T : '__invalid_negative_number__'

    

El error está en la línea: // Verificar el tipo de propiedad de la función de entrada checkFields<Diff<PageProps, FirstArg<TEntry['default']>, 'default'>>()

No sé qué estaba haciendo mal y no sé cómo arreglarlo. Revisé cómo uso mis props y está bien. Puedes revisar el código a continuación de mi componente InputForm.tsx y verás cómo establezco los props (tengo un archivo separado con interfaces):

      'use client'
import React, { useState } from "react";
import styles from './inputform.module.scss';
import { InputFormProps } from "../../actions/Interface";


const InputForm: React.FC<InputFormProps> = ({ type, placeholder }) => {
  const [inputType, setInputType] = useState(type);

  const toggleInputVisibility = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault(); // Prevent the modal from closing
    setInputType(currentType => (currentType === "password" ? "text" : "password"));
  };

  return (


    <div className={styles.inputForm}>
      <input
        type={inputType}
        placeholder={placeholder}
        className={styles.inputBlock} />


      {type === "password" && (
        <button
          onClick={toggleInputVisibility}
          className={styles.hidePasswordIcon}
          aria-label={inputType === "password" ? 'Show password' : 'Hide password'}
        >
          {inputType === "password" ? (

            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M1 12C1 12 5 4 12 4C19 4 23 12 23 12C23 12 19 20 12 20C5 20 1 12 1 12Z" stroke="#505050" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              <path d="M12 15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15Z" stroke="#505050" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          ) : (

            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
              <g clipPath="url(#clip0_150_2589)">
                <path d="M17.94 17.94C16.2306 19.243 14.1491 19.9649 12 20C5 20 1 12 1 12C2.24389 9.68192 3.96914 7.65663 6.06 6.06003M9.9 4.24002C10.5883 4.0789 11.2931 3.99836 12 4.00003C19 4.00003 23 12 23 12C22.393 13.1356 21.6691 14.2048 20.84 15.19M14.12 14.12C13.8454 14.4148 13.5141 14.6512 13.1462 14.8151C12.7782 14.9791 12.3809 15.0673 11.9781 15.0744C11.5753 15.0815 11.1752 15.0074 10.8016 14.8565C10.4281 14.7056 10.0887 14.4811 9.80385 14.1962C9.51897 13.9113 9.29439 13.572 9.14351 13.1984C8.99262 12.8249 8.91853 12.4247 8.92563 12.0219C8.93274 11.6191 9.02091 11.2219 9.18488 10.8539C9.34884 10.4859 9.58525 10.1547 9.88 9.88003" stroke="#505050" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
                <path d="M1 1L23 23" stroke="#505050" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
              </g>
              <defs>
                <clipPath id="clip0_150_2589">
                  <rect width="24" height="24" fill="white" />
                </clipPath>
              </defs>
            </svg>
          )}
        </button>
      )}
    </div>
  );
}

export default InputForm;

Por favor, ayuda. Ya pasé mucho tiempo en esto, el plazo es pronto

Respuesta #1

Elementos exportados: En un archivo page.tsx, solo se pueden exportar ciertas cosas, a saber:

default: El componente principal exportado que representa la página. metadata: Opcional, para definir metadatos para la página. generateStaticParams: Opcional, para generar parámetros estáticos para la página (en el caso de rutas dinámicas).

Si cambias el nombre de tu archivo a algo diferente de page.tsx, podría funcionar.

Respuesta #2

Verifica si estás usando la sintaxis async/await con un componente de página de función flecha. Si lo estás haciendo, puedes intentar convertirlo en una función con nombre. Eso es lo que hice para solucionar un problema similar en mi proyecto.

Artículos relacionados