【问题标题】:How to print out all types of properties of a type in TypeScript?如何在 TypeScript 中打印出一个类型的所有类型的属性?
【发布时间】:2021-09-18 16:12:56
【问题描述】:

我想在 TypeScript 中打印出一个类型的所有类型的属性。例如,我想记录AddressWithUnit 有哪些属性以及属性的类型。在下面的代码中,手动检查它可能很简单。但是,如果一个类型与多个类型组合在一起,手动检查可能会很复杂。

type BasicAddress = {
  name?: string;
  street: string;
  city: string;
  country: string;
  postalCode: string;
}

interface AddressWithUnit extends BasicAddress {
  unit: string;
}

【问题讨论】:

  • 接口(以及类型系统的其余部分)在运行时不存在。您不能在运行时对编译时构造进行动态查找。
  • 正如@VLAZ 所说,这是不可能的。您可以创建一个抽象类来反映您的类型别名,但是如果您需要在运行时引用类型。
  • 那么我将如何在编译时检查它?只要我能检查类型,这对我有好处。

标签: typescript types interface


【解决方案1】:

那么我将如何在编译时检查它?只要我能检查类型,这对我有好处。

(回答时记住你的这个评论)

我不确定您的确切要求是什么,但我们假设您要确保所有值的类型均为 stringnumberundefined。所以你可以做这样的事情......

type BasicAddress = {
  name?: string;
  street: string;
  city: string;
  country: string;
  postalCode: string;
}

interface AddressWithUnit extends BasicAddress {
  unit: string;
}
type TestAddressWithUnit = TestTrue<
  Value<AddressWithUnit> extends string | number | undefined
    ? true
    : false
>;

type Value<T> = T[keyof T]
type TestTrue<T extends true> = T;

现在,如果您在 AddressWithUnit 的定义中错误地将 unit 设为 boolean,则代码将无法编译,并且您将在 TestAddressWithUnit 处收到错误,例如 so

现在像我这样的人甚至可以进行元编程,我可以编写代码给我error in natural language...抱歉炫耀:P

【讨论】:

  • "现在,如果您错误地将 unit 设为布尔值,则代码将无法编译,并且您将在 TestAddressWithUnit 处收到错误" 如果您只使用 TS,这也是其工作方式类型:Playground Link
  • @VLAZ 用户想要测试类型定义本身而不是分配给它的值。我已经用更精确的措辞更新了答案,链接到操场,以显示我在说什么错误。 Here's the same
  • facepalm 我完全误读了 OP 的最后一条评论。我以为它说他们想在运行时检查它。
猜你喜欢
  • 2022-09-24
  • 2020-03-10
  • 2019-07-27
  • 1970-01-01
  • 2021-12-08
  • 2019-12-03
  • 1970-01-01
  • 2022-01-10
  • 2020-11-11
相关资源
最近更新 更多