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

180
Visualizações
decoding typescript ternary operator

I came across some code in the typescript docs that is confusing for me.

function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

Can anybody explain what's going on in the return statement? Is that a ternary operator?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

First, analyze the declared return type -1 | 0 | 1:

This is a union of Literal types [see docs for reference]. This indicates that the return type of this function will be either:

  • the number -1,
  • the number 0,
  • or the number 1.

Now analyze the return statement in the function return a === b ? 0 : (a > b ? 1 : -1);:

This is a 'nested' JavaScript Ternary Operator [see docs for reference].

The expression before the ? is evaluated first; If it is evaluated to true then the expression before the : is evaluated, if false then the expression after the : is evaluated.

It is equivalent to the follow if statement:

if (a === b) {
  return 0;
} else {
  if (a > b) {
    return 1;
  } else {
    return -1;
  {
}

or put more simply:

if (a === b) {
  return 0;
} else if (a > b) {
  return 1;
} else {
  return -1;
{
about 4 years ago · Juan Pablo Isaza Relatório

0

Think of it like this:

function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : (a > b ? 1 : -1);
}

If a === b, return 0. Otherwise, is a > b? If so, return 1. Otherwise, return -1. Might be easier to think of like this:

function compare(a: string, b: string): -1 | 0 | 1 {
  if (a === b) {
    return 0;
  } else {
    if (a > b) {
      return 1;
    } else {
      return -1;
    }
}

Although that's the way I think about it, this is the way I'd write the code with if statements (remember, all three of these are equivalent):

function compare(a: string, b: string): -1 | 0 | 1 {
  if (a === b) {
    return 0;
  } else if (a > b) {
    return 1;
  } else {
    return -1;
  }
}
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