我想根据TypeScript中另一个对象的键创建一个类型。
我已经设法通过类型推断做到了这一点。但是如果我使用显式类型Record<string, something>,那么keyof会给我string,而不是我使用的实际键的联合。
示例代码如下:
type FileType = "image" | "video" | "document";
type FileTypeList = Record<string, FileType>
const inferedFileList = {
a: "image",
b: "video",
c: "document"
}
//type files = "a" | "b" | "c"
type files = keyof typeof inferedFileList;
const explicitelyTypedList : FileTypeList = {
a: "image",
b: "video",
c: "document"
}
//type typedFiles = string
type typedFiles = keyof typeof explicitelyTypedList;Relevant TypeScript Playground
有没有什么方法可以让我在使用Record<string, something>格式的显式类型的同时,仍然使用keyof的联合类型?我想可以使用一个行为类似typeof的关键字,但使用对象的形状而不是其声明的类型,但是TypeScript实现了这样的东西吗?
发布于 2020-12-12 06:36:01
类型推断在TypeScript中非常强大,不自己注释类型也没什么错。
当您显式键入对象时,实际上键入它的精确度较低:
const aString = "a" as const; // typeof aString is 'a'
const justString: string = aString; // typeof justString is 'string'也许您在稍后的过程中需要此类型,因此您可以执行以下操作:
type FileTypeRecord = Record<keyof typeof inferedFileList, FileType>因此,只使用现有的键(a,b,c)获取整个记录类型
如果您希望保护对象具有有效值但又具有静态已知密钥,您可以尝试此方法:
type FileType = "image" | "video" | "document";
function getTypedFileObject<T extends { [k: string]: FileType }>(blueprint: T) : Record<keyof T, FileType> {
return blueprint;
}
const obj = getTypedFileObject({
a: "image",
b: "video",
c: "document",
// d: "test" will not compile
})发布于 2020-12-12 22:04:54
也许它会对你有所帮助:
type FileType = "image" | "video" | "document";
const inferedFileList = {
a: "image",
b: "video",
c: "document"
}
type FileTypeList = Record<keyof typeof inferedFileList, FileType>
const explicitelyTypedList : FileTypeList = {
a: "image",
b: "video",
c: "document"
}
//type typedFiles = string
type typedFiles = keyof typeof explicitelyTypedList; // a | b | chttps://stackoverflow.com/questions/65259086
复制相似问题