(对不起标题,我知道这不好)
我有一个 A 或 B 类型的实例。我想创建一个函数(或 whateva),它接受 A 或 B 并返回其包装参数。即
type A = { name: string };
type B = A[];
type DucktypedA = { // idc how this struct looks like as we can differentiate between A and B
a: A,
};
type DucktypedB = {
b: B,
}
function test(arg: A | B): DucktypedA | DucktypedB {
if (arg instanceof A) {
return { a: arg };
} else {
return { b: arg };
}
}
这在打字稿中有可能吗?
const a = { name: "me" };
const wrappedA = test(a); // --> { a: { name: "me" } }
const b = [{ name: "me" }];
const wrappedB = test(b); // --> { b: [{ name: "me" }] }
instanceof
不适用于打字稿类型。
您可以使用类型保护功能将“类型检查”带入运行时领域。 玩
function isA(v: any): v is A {
return 'name' in v
}
function test(arg: A | B): DucktypedA | DucktypedB {
if (isA(arg)) {
return { a: arg };
} else {
return { b: arg };
}
}