所以從技術上講,我已經找到了這個問題的答案,但我正在尋找一種更簡潔的方法。同樣,我還沒有看到任何特別說明如何執行此操作的 SO 問題或檔案。
首先,舉個例子:我知道如果我有一個型別化陣列,我可以通過這種方式推斷每個值的型別:
// just with types
type Tuple = [item1: number, item2: string];
type Item1Type = Tuple[0]; // type is number
type Item2Type = Tuple[1]; // type is string
// or with `typeof`
const myTuple: Tuple = [1, 'one'];
type InferredItem1Type = typeof myTuple[0]; // type is number
type InferredItem2Type = typeof myTuple[1]; // type is string
如果我有一個這樣的泛型并且我可以訪問的是這種型別的實體:
// the generic type
type GenericObjectWithList<T> = {
list: T[];
};
// the instance i have access to
const object: GenericObjectWithList<string> = {
list: ['one', 'two', 'three'],
};
我想推斷內部串列的型別。
// infer the type of the list
type InferredListType = typeof object['list'][0]; // type is string
如您所見,我已經發現我可以推斷出類似于第一個示例中的方法的這種型別,但我想知道,是否有更簡潔的方法來推斷這種型別?我希望有一種方法可以推斷串列的單值型別而無需執行[0]. 如果沒有另一種方法可以做到這一點,有人會介意解釋為什么這種方法是我們希望它成為推斷陣列值型別的唯一方法嗎?
uj5u.com熱心網友回復:
- 專案清單
陣列由 a 索引number,這意味著您可以鉆取陣列以number從該陣列中獲取值型別。
ArrayType[number]通常是您將如何執行此操作。用零索引非元組陣列幾乎是同一件事,但它向程式員暗示索引值對于不同的數字會有所不同,這是不對的。
type StrArr = string[]
type ArrVal = StrArr[number] // string
或從您的代碼:
type InferredListType = typeof object['list'][number]; // type is string
操場
這也適用于元組。
type MyTuple = [123, 'asd']
type TupleVal = MyTuple[number] // 123 | 'asd'
但是,當然,您丟失了該元組中每種型別的位置資訊。如果你需要,這就是你會用[0],[1]等,來代替。
操場
uj5u.com熱心網友回復:
TL; 博士 typeof object['list'][number]
您可以使用型別索引型別時指數,而不是字面的價值。這適用于任何可索引物件。
所以,如果你有
const object = {
list: ['one', 'two', 'three'],
};
您可以list像這樣推斷該屬性的型別:
type InferredListType = typeof object['list'][number]; // note that `number` instead of `0`
更好的是,您可以使用keyof來獲取該索引型別:
type InferredListElementType = object['list'][keyof object['list']];
但是,如您所見,對于超過單層嵌套的任何內容,這可能非常冗長。但不要忘記keyof:它是一個強大的工具。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364351.html
上一篇:使用makestyles@mui時,型別“字串”上不存在屬性“”
下一篇:通過減少和陣列回傳物件陣列
