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

168
Visualizações
How to set Conditional type for one parameter with literal type of another parameter of the function

There is a simple function that select something by name or index

async function(value:number|string, by: 'index'|'name' = 'index'){
 switch(by){
  case 'index':{
    selectby(value)
  };
  case 'name':{
    selectby(value)
  } 
 }
}

is there a way to tell value type number if by is 'index' or not passed , else string

I have tried with function overloading:

 async function(value:number, by?: 'index' = 'index')
 async function(value:string, by: 'name' = 'index')
 async function(value:number|string, by: 'index'|'name' = 'index')

the problem is that , the implementation where async function(value:number|string, by: 'index'|'name' = 'index') doesn't shows up on hovering the function. It shows the first override as the default function

How can i give a typescript documentation that if 'if index then number' else string

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

0

Your async example works just fine:

async function test(value:number, by: 'index'): Promise<void>;
async function test(value:string, by: 'name'): Promise<void>;
async function test(value:number|string, by: 'index'|'name' = 'index'): Promise<void> {
 }

test('test', 'name') // works
test(1, 'name') // does not work
test(1, 'index') // works
test('aa', 'name') // does not work

Your IDE will suggest the first function overload type by default, but as soon as you add a string as the first parameter, it should then suggest the user to add name as the second parameter. enter image description here

You can find the playground example in the following link.

about 4 years ago · Juan Pablo Isaza Relatório

0

What about using typeof? Then you don't need the by parameter at all:

switch(typeof value) {
    case "number": {
        selectBy(value)
    }
    case "string": {
        selectBy(value)
    }
}

Alternatively, you can compose your parameters as a custom object type, incorporating your stated constrains. This way, you will be forced to pass the right by for the value type. However, this will lead to only one parameter passed to your function:

type Value1 = { value: number, by: 'index' } | { value: string, by: 'name' }
const getValue1 = async function ({ value, by }: Value1) {
    switch (by) {
        case 'index': {
            selectby(value)
        };
        case 'name': {
            selectby(value)
        }
    }
}

getValue1({ value: 1, by: 'index' })

The same is possible for an array type:

type Value2 = [number, 'index'] | [string, 'name']
const getValue2 = async function ([value, by]: Value2) {
    switch (by) {
        case 'index': {
            selectby(value)
        };
        case 'name': {
            selectby(value)
        }
    }
}

getValue2([ 1, 'index' ])

TypeScript Playground


edit: Hovering and typing hints depend on your used IDE. Normally, you can switch the displayed signature using some arrow buttons at the sides:

there are arrows to the left to show other overloads

I am not aware of any mechanism to tell the IDE in which order to display the overloads.

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