我對 TypeScript 中更高級的泛型型別有疑問。
我想要做的是一組資料,其中data本身由以下控制type:
[
{
type: "T1",
content: number,
},
{
type: "T2",
values: {
id: number,
...
}
}
]
在描述了可用的型別后,我有點堆積如山:
enum DataType {
T1 = "t1",
T2 = "t2"
}
所以結果一定是這樣的,我猜:
interface DataGeneric<T> {
[T extends DataType.T1]: { content: number },
[T extends DataType.T2]: { values: { id: number, ... } },
} ???
interface Data<T extends DataType = any(?)> extends DataGeneric<T>{
type: DataType,
// and all the other fields are generic from T = DataType
}
const someData: Data[] | undefined = fetchData();
// suggesting that the `type` of element[1] is "t2"
// and VSCode suggestions works correctly too,
// consider that there is an object-field `values` with `id` key
someData[1].values.id
提前致謝!
uj5u.com熱心網友回復:
如果您type根據字串或數字文字檢查物件的屬性以區分物件的其余部分所持有的資料型別,那么您可能希望使用可區分的聯合而不是泛型。這基本上是一種聯合型別,其中聯合的成員有一個共同的判別鍵。在您的情況下,它可能如下所示:
enum DataType {
T1 = "t1",
T2 = "t2"
}
type Data =
{ type: DataType.T1, content: number } |
{ type: DataType.T2, values: { id: number } }
然后當你有一個datatype的值時Data,你可以檢查它的type屬性,編譯器知道它應該縮小data到聯合的正確成員:
declare const someData: Data[] | undefined;
if (someData) {
someData.forEach(data => {
if (data.type === DataType.T1) {
data.content.toFixed();
} else {
data.values.id.toFixed();
}
})
}
Playground 鏈接到代碼
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389721.html
上一篇:實作協議的Python泛型型別
