简体   繁体   English

是否可以从字符串模板文字中推断泛型类型

[英]Is it possible to infer generic type from inside string template literal

The following piece of code does exactly what I intend to know with one caveat, I would like to avoid having to explicit the generic it needs.下面的一段代码完全符合我的意图,但需要注意的是,我想避免必须明确说明它需要的泛型。

type EventGroup = {
  actions: "run" | "save"
  other: "bla"
}

export type EventType<T extends keyof EventGroup> = `${T}/${EventGroup[T]}`

const t: EventType<"actions"> = "actions/run"

I would like Typescript to infer that:我想 Typescript 推断:

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

Which is what this code does but with an explicit generic.这就是这段代码的作用,但带有显式泛型。

You can do that with a mapped type you then take a union of the values from:您可以使用映射类型执行此操作,然后从以下位置获取值的联合:

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

Testing the validity of the type:测试类型的有效性:

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

Playground link 游乐场链接

There are two parts to that, first the mapped type:有两个部分,首先是映射类型:

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

which evaluates as:评估为:

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

Then we use [keyof EventGroup] on the end to extract just the values of actions and other as a union.然后我们在最后使用[keyof EventGroup]来提取actions的值和other作为联合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM