如何在 TypeScript 中打印出一个类型的所有属性类型?
我想在 TypeScript 中打印出一个类型的所有属性类型。例如,我想记录 AddressWithUnit 有哪些属性以及这些属性的类型。在下面的代码中,手动检查它可能很简单。然而,如果一个类型是由多个类型组合而成的,手动检查可能会比较复杂。
type BasicAddress = {
name?: string;
street: string;
city: string;
country: string;
postalCode: string;
}
interface AddressWithUnit extends BasicAddress {
unit: string;
}
答案#1
那我该如何在编译时检查它呢?只要我能检查类型,对我来说就好了。
(在回答时记住你的这条评论)
我不确定你在这里的具体要求是什么,但我们假设你想确保所有值的类型都是 string、number 或 undefined。所以你可以这样做...
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 处得到如下错误
现在像我这样的人甚至可以进行元编程,我可以编写会以自然语言给我错误的代码……抱歉炫耀一下 :P
