簡體   English   中英

是否可以從字符串模板文字中推斷泛型類型

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

下面的一段代碼完全符合我的意圖,但需要注意的是,我想避免必須明確說明它需要的泛型。

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]來提取actions的值和other作為聯合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM