[英]TypeScript: Can I infer number index value type?
I created a helper function to convert an object of numbered keys to a Map:我创建了一个助手 function 来将编号键的 object 转换为 Map:
interface IndexedObject {
[index: number]: unknown;
};
const objectToIndexedMap = (indexedObject: IndexedObject) => new Map(
Object.entries(indexedObject).map(
([ index, field ]) => [ Number(index), field ]
)
);
I use it to convert objects I'm getting from the API to a more convenient Map, where I don't need to deal with string keys anymore.我用它将我从 API 获得的对象转换为更方便的 Map,我不再需要处理字符串键。 The problem is that the returned type is Map<number, any>
, while I'd like to use the type of those values in IndexedObject
.问题是返回的类型是Map<number, any>
,而我想在IndexedObject
中使用这些值的类型。
Is it possible to get that type and make my function return this specific type for Map values?是否有可能获得该类型并使我的 function 为 Map 值返回该特定类型?
So for example this would throw an error:因此,例如这会引发错误:
interface IndexedNumbers {
[index: number]: number;
}
const indexedNumbers: IndexedNumbers = api.numbers; // pseudocode
const map = objectToIndexedMap(indexedNumbers);
const foo = map.get(0)!.toUpperCase(); // This should throw an error
Of course I know I can hard-type it:当然我知道我可以硬输入它:
const map: Map<number, number> = objectToIndexedMap(indexedNumbers);
But I'd love TypeScript to do that for me.但我很乐意 TypeScript 为我做这件事。 Is it possible?可能吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.