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

118
Visualizações
method that takes parameter of multiple type and decide the behavior at runtime

I have a method like this

square(num: number | string): number {
 // 
}

In this method I want to check the parameter's data type and invoke the logic accordingly. How do to that in TS?

Edit:

Specific types in question

export type KV<T extends string | number> = {
    key: string;
    val: T;
}
export type LogicalKV<T extends string | number> = {
    logicalOperator: LogicalOperator
    filters?: Filter<T>[];
    logicalFilters?: LogicalFilter<T>[];
}

Function

class Foo {

    read(filter: KV<string | number> | LogicalKV <string | number>):  Promise<void> {
    // if filter is of KV do this, else do that
   }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Types are stripped at runtime unfortunately. But you could go the good old way of typeof

if (typeof num === "string") {/*it's string here*/} else {/*it's number here*/}

Typescript will also understand that and coerce to an appropriate type in each branch.

In case of custom types, like yours, it's going to be a bit different. Algebraic data types are involved. It's also not too pretty when you instantiate it, but you have to deal with passing runtime string "kinds" one way or another.

export type KV = {
  kvField: string;
  kind: "kv";
};
export type LogicalKV = {
  logicalKvField: number;
  kind: "logicalKv";
};

const KVInstance: KV = {
  kind: "kv",
  kvField: "foo"
};

const LogicalKVInstance: LogicalKV = {
  kind: "logicalKv",
  logicalKvField: 1
};

type FilterArg = KV | LogicalKV;

const fn = (f: FilterArg) => {
  switch (f.kind) {
    case "kv":
      // ts knows it's KV
      f.kvField;
      return;
    case "logicalKv":
      // ts knows it's LogicalKV
      f.logicalKvField;
      return;
  }
}
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