typescript - 在 TypeScript 中,我可以根据索引器键的窄类型来限制索引器值的类型吗?
问题描述
解决方案
我也一直在寻找这个。我在 TypeScript 中进行了一些实验,并提出了这个解决方案:
type ObjectWithKey<obj extends {[key: string]: any}> = {
[k in keyof obj]: {key: k};
}
declare function createObjectWithKeys<T extends {[key: string]: any} & ObjectWithKey<T>>(input: T): T;
// This does not compile
const x = createObjectWithKeys({
a: 1,
b: {key: 'c'},
c: {key: false}
})
// This does compile
const x = createObjectWithKeys({
a: {key: 'a'},
b: {key: 'b'},
c: {key: 'c'}
})
推荐阅读
- reactjs - 使用 json 数据回调后设置状态
- node.js - 如何在没有冒号的节点js中获取时间戳
- flutter - 图片未显示在图库中
- javascript - 未从 openlibrary.org api 获取图书数据
- oracle - 在分层数据结构中列出一个孩子的所有祖先
- php - 如何对laravel中的对象数组进行排序?
- python - 1 列有一个 int。另一个有一个整数列表。如何将数据帧转换为这些对的 numpy rec 数组?
- sql - AWS Redshift SQL - PIVOT 查询(一行/行多次计数)
- typescript - TSLint object-literal-sort-keys 按字母顺序排序,但错误仍然存在
- python - 从列表和字典中抓取网页