Javascript 在Typescript中为映射键入guard
在文件Javascript 在Typescript中为映射键入guard,javascript,typescript,Javascript,Typescript,在文件CategoryMap.ts export default new Map<number, SubCategory[]>([ [11, [100, 101]], [12, [102, 103]], ... ]) 这不起作用,因为CategoryMapId是 “[Symbol.toStringTag]”|“clear”|“delete”|“forEach”|“get”|“has”|“set”|“size”|“[Symbol.iterator]”|“entrie
CategoryMap.ts
export default new Map<number, SubCategory[]>([
[11, [100, 101]],
[12, [102, 103]],
...
])
这不起作用,因为CategoryMapId
是
“[Symbol.toStringTag]”|“clear”|“delete”|“forEach”|“get”|“has”|“set”|“size”|“[Symbol.iterator]”|“entries”|“keys”|……
我希望类型CategoryMapId
是11 | 12…
有什么解决办法吗?Thanx.您可以为地图的“键”提供如下类型:
const testMap=新映射([
[11, [100, 101]],
[12, [102, 103]],
]);
consty=testMap.get(11);//作品
const x=testMap.get(13);//类型错误
然而,您似乎希望让typescript在运行时推断出这一点。现在看来,我们可以做如下事情:
type KeyOfMap=M扩展映射?K:从来没有
const testMap=新映射([
[11, [100, 101]],
[12, [102, 103]],
]);
类型CategoryMapId=KeyOfMap;
const isCategoryId=(id:number):id为CategoryPID=>
has(id);
但是在这种情况下,CategoryMapId
仍然只有类型number
,这不是我们想要的
使用对象而不是贴图,可以选择为关键帧获取适当的类型:
const testMap={
11: [100, 101],
12: [102, 103],
}
类型CategoryMapId=typeof testMap的键;
const isCategoryId=(id:number):id为CategoryPID=>
Object.keys(testMap).map(Number).indexOf(id)>-1;
常数x=isCategoryId(11);//真的
常数y=isCategoryId(13);//假的
const getValue=(id:number)=>{
如果(isCategoryId(id)){
返回testMap[id];
}否则{
返回[];
}
}
这可能不适合您的用例,但目前似乎不可能在地图上实现这一点是的,我认为对象是实现这一点的唯一方法。但可能更好的类型是这样的:testMap中的
返回id,而不是Object.keys(testMap.map(…)…
import categoryMap from 'CategoryMap'
type CategoryMapId = keyof typeof categoryMap
function isCategoryId(id: number): id is CategoryMapId {
return categoryMap.has(id)
}