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
}
}
CodePudding user response:
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;
}
}