Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda