Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!