可以在编译时增加 ducktype 信息吗?

问题描述 投票:0回答:1

(对不起标题,我知道这不好)

我有一个 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" }] }
typescript
1个回答
0
投票

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 };
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.