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

110
Visualizações
Narrow down primitive return type of function at call site in Typescript

Writing a function that can take an any value and returns only boolean or number in typescript, it all works fine, until we need to narrow down the return value of the function at the call site to suit some variable type(or parameter type in case of functions compositions)

Here's the function

function parseValue(value: any, defaultValue: number | boolean): number | boolean {

    const valueType = typeof value;


    switch (valueType) {
        case 'undefined': {
            return defaultValue;
        }

        case 'boolean': {
            return value;
        }

        default: {

            if (value == 'Unlimited')
                return Infinity;

            return parseInt(value);
        }
    }

}

The problem is seen at call site

let booleanResult = parseValue(true, true);

// Error: type boolean | number is not assignable to type boolean
let booleanCondition: boolean = booleanResult;


let numberResult = parseValue(2, 1);

// Error: type boolean | number is not assignable to type number
let numberValue: number = numberResult;

Is there a way in typescript which allow us to specify the return type at call site?


Overloading is not compatible! It looks like I can't make on overload a function with different param type(correct me if I'm wrong here)

type returnType = boolean | number;

// This overload signature is not compatible with its implementation signature

function parseValue(value: any, defaultValue:  boolean):  returnType;
function parseValue(value: any, defaultValue: number ): returnType{
 ...
}

I know we can parse the output of the function again to make it works like:

let numberValue: number = Number(numberResult);

But I'm looking for a typescript solution for this problem.

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

0

Use typescript overload the proper way:

From Typescript docs

The signature of the implementation is not visible from the outside. When writing an overloaded function, you should always have two or more signatures above the implementation of the function.

The solution was easily done writing each overload function alone, then writing the body of the function

function parseValue(value: any, defaultValue: number): number;
function parseValue(value: any, defaultValue: boolean): boolean;
function parseValue(value: any, defaultValue: number | boolean): boolean | number {
 ... body of function
}

My problem was solved when I've read

Again, the signature used to write the function body can’t be “seen” from the outside.

So I was kind of merging the overload with the implementation, where we should have separated them

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