【发布时间】:2022-11-13 08:30:34
【问题描述】:
我有以下类型的对象,我需要一个 TypeScript 助手来获取字段名的类型:
const config: FormConfig = [
{
type: "row",
content: [
{
type: "text",
name: "firstName",
fieldConfig: {
label: "First Name",
},
},
{
type: "text",
name: "lastName",
fieldConfig: {
label: "Last Name",
},
},
],
},
]
export interface FormRowConfig {
type: "row";
content: FormEntryConfig[];
}
export interface FormFieldText {
type: "text";
name: string;
...
}
export type FormEntryConfig = FormRowConfig | FormFieldText // plus other fields;
export type FormConfig = FormEntryConfig[];
我尝试了以下方法来获取条目的名称,但我得到“类型实例化过深并且可能无限”。 (我猜这是有道理的):
type SomeHelper<Entry extends FormEntryConfig> = Entry extends FormFieldConfig
? Entry["name"]
: Entry extends FormRowConfig
? SomeHelper<Entry>
: never;
我什至能够得到例如"firstName" 是这样的类型,因为配置是强类型的并且名称设置为字符串?
我如何实现这样的目标?
type Name = SomeHelper<typeof config> // "firstName" | "lastName"
【问题讨论】:
-
您可以将所有这些类型添加到TypeScript playground 中以便我们重现它吗?
-
可以创建这样的类型。请参阅此Playground。但是需要做一些修改,比如去掉
config的类型注解,增加as const。这会回答你的问题吗? -
@TobiasS。是的,这有很大帮助,谢谢!
-
@JohnnyKontrolletti - 很高兴听到:)让我写一个答案
标签: typescript