到現在為止我有這個(缺少實作在這里并不重要):
interface Context {
User: "OK" | "KO" // | "..."
Password: "valid" | "invalid" // | "..."
Message: "Welcome" | "Invalid credentials" // | "..."
// ...
}
// I = Input, O = Output, H = Header
declare var I :Context , O :Context
interface Examples<H extends unknown[]> { // by @jcalz :)
(...rows: H): Examples<H>
}
// this syntax is function chain with type safety and autocomplete
declare function Examples<H extends unknown[]>(...rows: H): Examples<H>
Examples
( I.User , I.Password , O.Message )
( "OK" , "valid" , "Welcome" )
( "KO" , "invalid" , "Invalid credentials" )
declare var ExamplesTTL_ideal: any
// and this is ideal syntax sample with TTL - where first param is header and rest should be rows of type header
ExamplesTTL_ideal `
${[ I.User , I.Password , O.Message ]}
${[ "OK" , "valid" , "Welcome" ]}
${[ "KO" , "invalid" , "Invalid credentials" ]}
`
這一切都在Typescript Playground
問題是 - ExampleTTL_ideal 而不是 :any 的宣告應該是什么?
問候。
uj5u.com熱心網友回復:
我的方法如下所示:
declare function ExamplesTTL<H extends string[]>(
text: TemplateStringsArray, ...rows: [...H][]): ExamplesTTL<H>;
interface ExamplesTTL<H extends string[]> {
(text: TemplateStringsArray, ...rows: [...H][]): ExamplesTTL<H>;
}
該函式是通用的 in H
,旨在成為字串文字型別的元組(或字串文字的聯合)。我們想成為一個這樣的元組的陣列。如果幸運的話,編譯器將使用陣列中的第一個元素進行推斷,然后檢查陣列中的后續元素是否符合它。rows
rows
H
請注意,為了給編譯器一個H
應該是元組的提示,我們使用可變元組型別 [...H]
。
由于您希望函式回傳相同型別的函式,但H
不再是泛型的,所以我定義了ExamplesTTL<H>
泛型型別。從概念上講,該ExamplesTTL<H>
型別等同于typeof ExamplesTTL<H>
實體化運算式,但我給它起了一個新名稱以避免惡性回圈(參見ms/TS#51202)。
讓我們測驗一下:
const x = ExamplesTTL`
${[I.User, I.Password, O.Message]}
${["OK", "valid", "Welcome"]}
${["KO", "invalid", "Invalid credentials"]}
`;
// const x: ExamplesTTL<["OK" | "KO", "valid" | "invalid",
// "Welcome" | "Invalid credentials"]>
x`${["OK", "valid", "Welcome"]} ${["oops"]}`; // error!
// ------------------------------> ~~~~~~
//Type '"oops"' is not assignable to type '"OK" | "KO"'.(2322)
const y = ExamplesTTL`
${["a", "b", "c"]}${["a", "b", "d"]}`; // error!
// --------------------------> ~~~
// Type '"d"' is not assignable to type '"c"'.(2322)
看起來不錯。的型別x
是根據需要推斷的ExamplesTTL<["OK" | "KO", "valid" | "invalid", "Welcome" | "Invalid credentials"]>
,因此后續呼叫將x
其輸入限制為該型別(所以["oops"]
很糟糕)。如果您嘗試ExamplesTTL
使用不一致的元組型別進行呼叫,則后續陣列條目中的任何不一致都會被標記為錯誤。
Playground 代碼鏈接
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516216.html
標籤:打字稿打字稿泛型模板文字
上一篇:根據其他型別反應打字稿型別