是否有可能从字符串模板文字内部推断泛型类型?



下面这段代码正是我想要知道的,但有一点需要注意,我希望避免必须显式显示它所需的泛型。

type EventGroup = {
actions: "run" | "save"
other: "bla"
}
export type EventType<T extends keyof EventGroup> = `${T}/${EventGroup[T]}`
const t: EventType<"actions"> = "actions/run"

我希望Typescript可以推断:

`actions/run` -> valid
`actions/save` -> valid
`actions/bla` -> NOT valid
`other/bla` -> valid

这就是这段代码所做的,但带有显式泛型。

您可以使用映射类型然后从

获取值的并集
export type EventType = {
[Key in keyof EventGroup]: `${Key}/${EventGroup[Key]}`
}[keyof EventGroup];

测试类型的有效性:

const t1: EventType = "actions/run";  // valid
const t2: EventType = "actions/save"; // valid
const t3: EventType = "actions/bla";  // NOT valid
const t4: EventType = "other/bla";    // valid

操场上联系

有两部分,第一部分是映射类型:

type EventType = {
[Key in keyof EventGroup]: `${Key}/${EventGroup[Key]}`
}

的计算结果为:

type EventType = {
actions: "actions/run" | "actions/save";
other: "other/bla";
}

然后我们在最后使用[keyof EventGroup]来提取actionsother的值作为一个并集。

最新更新