Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
Definición de <número | ''> en mecanografiado

A continuación se muestra mi código.

 const [enteredAge, setEnteredAge] = useState<number | "">("");

Ha definido el tipo para useState como número. Tener un tipo como <number | undefined> tiene sentido que definamos el tipo como number o undefined . Pero en el código anterior he definido <number|""> de esta manera. ¿Significa esto que solo el estado inicial de useState se puede definir "" de esta manera?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Con useState<number | "">(""); su estado se establecerá inicialmente en "" y luego se puede establecer en un número o "" nuevamente, pero no en cualquier otra cadena.

También puede inicializarlo a un número useState<number | "">(42); de la misma manera

 const [state, setState] = useState<number | "">(""); const [stateNum, setStateNum] = useState<number | "">(42); setState("Foo"); // Error: Argument of type '"Foo"' is not assignable to parameter of type 'SetStateAction<number | "">'.ts(2345) setState(0); // OK setState(""); // OK
about 4 years ago · Juan Pablo Isaza Report

0

Si el uso es para mantener el valor de una entrada numérica controlada, no lo almacene en una sola variable de estado; en su lugar, almacene la entrada del usuario como un valor de cadena sin procesar y use un valor de estado separado para el tipo de número analizado. Al hacerlo, nunca modificará la entrada del usuario de una manera inesperada (ejemplo: intente ingresar 1e6 en la entrada en el ejemplo de código a continuación y vea cómo se analiza como un valor numérico:

Enlace de juegos TS

 <div id="root"></div> <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script><script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script><script src="https://unpkg.com/@babel/standalone@7.16.4/babel.min.js"></script><script>Babel.registerPreset('tsx', {presets: [[Babel.availablePresets['typescript'], {allExtensions: true, isTSX: true}]]});</script> <script type="text/babel" data-type="module" data-presets="tsx,react"> /** * The following line is here because this Stack Overflow snippet uses the * UMD module for React. In your code, you'd use the commented `import` lines * below it. */ const {useEffect, useState} = React; // import ReactDOM from 'react-dom'; // import {default as React, Dispatch, ReactElement, SetStateAction, useEffect, useState} from 'react'; type NumberParsingFunction = (input: string) => number; type NumericInputData = { rawValue: string; setRawValue: Dispatch<SetStateAction<string>>; value: number; }; const defaultNumberParsingFunction: NumberParsingFunction = str => Number(str); function useNumericInput (parseFn: NumberParsingFunction = defaultNumberParsingFunction): NumericInputData { const [rawValue, setRawValue] = useState(''); const [value, setValue] = useState(parseFn(rawValue)); useEffect(() => setValue(parseFn(rawValue)), [rawValue, setValue]); return {rawValue, setRawValue, value}; } function Example (): ReactElement { const {rawValue, setRawValue, value} = useNumericInput(); useEffect(() => console.log({rawValue, value})); return (<input type="number" onChange={ev => setRawValue(ev.target.value)} value={rawValue} />); } ReactDOM.render(<Example />, document.getElementById('root')); </script>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!