首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在对象形状上使用keyof而不是显式类型

问如何在对象形状上使用keyof而不是显式类型
EN

Stack Overflow用户
提问于 2020-12-12 05:49:59
回答 2查看 123关注 0票数 0

我想根据TypeScript中另一个对象的键创建一个类型。

我已经设法通过类型推断做到了这一点。但是如果我使用显式类型Record<string, something>,那么keyof会给我string,而不是我使用的实际键的联合。

TypeScript Playground GIF

示例代码如下:

代码语言:javascript
复制
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实现了这样的东西吗?

EN

回答 2

Stack Overflow用户

发布于 2020-12-12 06:36:01

类型推断在TypeScript中非常强大,不自己注释类型也没什么错。

当您显式键入对象时,实际上键入它的精确度较低:

代码语言:javascript
复制
const aString = "a" as const; // typeof aString is 'a'
const justString: string = aString; // typeof justString is 'string'

也许您在稍后的过程中需要此类型,因此您可以执行以下操作:

代码语言:javascript
复制
type FileTypeRecord = Record<keyof typeof inferedFileList, FileType>

因此,只使用现有的键(a,b,c)获取整个记录类型

如果您希望保护对象具有有效值但又具有静态已知密钥,您可以尝试此方法:

代码语言:javascript
复制
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
})
票数 0
EN

Stack Overflow用户

发布于 2020-12-12 22:04:54

也许它会对你有所帮助:

代码语言:javascript
复制
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 | c
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65259086

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档