Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda