Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
Defining <number | ''> in typescript

Below is my code.

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

Have defined the type for useState as number. Having a type like <number | undefined> makes sense that we definig the type to be number or undefined. But in the above given code I have defined <number|""> this way. Does this mean only initial state of the useState can be defined "" this way?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

With useState<number | "">(""); your state will be initially set to "" and then can either be set to a number or "" again but not any other string.

You can also initialise it to a number useState<number | "">(42); the same way.

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 Denunciar

0

If the use is for holding the value for a controlled numeric input, don't store it in a single state variable — instead, store the user input as a raw string value, and use a separate state value for the parsed number type. By doing so, you will never modify the user input in a way that's unexpected (example: try entering 1e6 into the input in the code example below and see how it's parsed as a numeric value:

TS Playground link

<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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda