采用多种类型参数并在运行时决定行为的方法
method that takes parameter of multiple type and decide the behavior at runtime
我有这样的方法
square(num: number | string): number {
//
}
在这个方法中,我想检查参数的数据类型并相应地调用逻辑。如何在 TS 中做到这一点?
编辑:
有问题的特定类型
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>[];
}
函数
class Foo {
read(filter: KV<string | number> | LogicalKV <string | number>): Promise<void> {
// if filter is of KV do this, else do that
}
}
不幸的是,类型在运行时被剥离。但是你可以走 typeof
的老路
if (typeof num === "string") {/*it's string here*/} else {/*it's number here*/}
Typescript 也会理解这一点,并在每个分支中强制转换为适当的类型。
对于像您这样的自定义类型,情况会有所不同。 Algebraic data types 参与。当你实例化它时它也不太漂亮,但你必须以一种或另一种方式处理传递运行时字符串“种类”。
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;
}
}
我有这样的方法
square(num: number | string): number {
//
}
在这个方法中,我想检查参数的数据类型并相应地调用逻辑。如何在 TS 中做到这一点?
编辑:
有问题的特定类型
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>[];
}
函数
class Foo {
read(filter: KV<string | number> | LogicalKV <string | number>): Promise<void> {
// if filter is of KV do this, else do that
}
}
不幸的是,类型在运行时被剥离。但是你可以走 typeof
if (typeof num === "string") {/*it's string here*/} else {/*it's number here*/}
Typescript 也会理解这一点,并在每个分支中强制转换为适当的类型。
对于像您这样的自定义类型,情况会有所不同。 Algebraic data types 参与。当你实例化它时它也不太漂亮,但你必须以一种或另一种方式处理传递运行时字符串“种类”。
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;
}
}