typescript - 打字稿检查字符串是否作为接口键存在
问题描述
我可以检查一个字符串是否作为接口键存在
interface list {
one: string
two: string
}
const myNumber = "one"
如何检查 myNumber 值是否是接口键
解决方案
为此,您需要有一些东西可以让您在运行时获取接口的密钥。Aninterface
在运行时不存在 - 它纯粹是一个 TypeScript 构造,因此它不存在于发出的代码中。
创建一个包含键的数组,声明它as const
以使其不会自动扩展类型,然后您就可以将其转换为List
类型。然后,您将拥有一个类型和一个运行时数组,您可以对其进行.includes
检查:
const listKeys = ['one', 'two'] as const;
type List = Record<typeof listKeys[number], string>;
// ...
const obj = {
one: 'one',
two: 'two',
three: 'three'
};
// Transformation to string[] needed because of an odd design decision:
// https://github.com/Microsoft/TypeScript/issues/26255
const newObj = Object.fromEntries(
Object.entries(obj).filter(
([key]) => (listKeys as unknown as string[]).includes(key)
)
);
推荐阅读
- c++ - 为什么在包含 boost 标头 (g++) 时出现“没有这样的文件或目录”错误
- mongodb - Mongo go驱动程序-在连接启用ssl和加密密钥时出现密钥不匹配错误
- javascript - Javascript - 获取两个数组之间的对应对象
- javascript - 尝试使用 Vue.js 访问 Stack Oveflow Api 出现错误
- android - 如何修复无法读取序列化文件指纹。在数据流中发现无法识别的值
- python - Django 无法登录用户
- python - 您可以自行签署 pyinstaller 程序,以便在将其提供给其他人时不会显示为病毒吗?
- java - 下载文件android的异常
- docker - Traefik 2 - 尝试将我的第一个容器配置为使用 traefik
- c# - 重新加载时重置分数