【发布时间】:2021-07-11 00:22:39
【问题描述】:
我推迟了很长时间,以为我会找到答案,但我仍然没有,所以我给了 SO 一个机会
import { PDFViewer, MSViewer } from './viewerclasses'
//tried adding in just a union of the keys
type ViewerTypes = 'xls' | 'xlsx' | 'doc' | 'docx' | 'pdf';
type PreviewTypes = {
pdf: typeof PDFViewer;
doc: typeof PDFViewer;
docx: typeof PDFViewer;
xls: typeof MSViewer;
xlsx: typeof MSViewer;
}
const previewTypes: PreviewTypes = {
pdf: PDFViewer,
doc: PDFViewer,
docx: PDFViewer,
xls: MSViewer,
xlsx: MSViewer
};
//attempt #1
type ViewerMap<T> = T extends ViewerTypes ? PreviewTypes[T] : false;
//attempt #2
type ViewerMaybe<T> = T extends keyof PreviewTypes ? PreviewTypes[T] : false
export function getViewer<K extends ViewerTypes>(filename: K): ViewerMaybe<typeof filename> {
const type = (filename.split('.').pop()?.toLowerCase() as ViewerTypes) || 'unknown';
const viewer = Object.prototype.hasOwnProperty.call(previewTypes, type) === true
? previewTypes[type]
: false;
return viewer;
}
但是我在这里只是在黑暗中拍摄,试图给 getViewer() 不同的类型、映射类型、索引访问类型等等,但是 TS 仍然不知道我在做什么。
我正在尝试正确键入 getViewer(),以便 Typescript 知道我是否将 previewTypes 的键作为参数提交,我会返回一个构造函数,如果没有,我会返回 false。我已经刷了这么久这个问题,但我想了解类型系统足以解决它。我知道有一种方法可以创建一个索引访问类型,其内容类似于
type ViewerIndexMap<T> = {
[Prop in keyof T]: Prop in keyof T ? T[Prop] : false
}
然后,
export function getViewer(filename): ViewerIndexMap<typeof filename>
或类似的东西
我哪里错了?我错过了什么?我刚刚重新阅读了 TS 手册,虽然我觉得映射类型很接近,但它们并没有让我准确地到达我需要的位置。
谢谢!
【问题讨论】:
标签: javascript typescript function indexing types