typescript - 基于对象定义 TypeScript 类型?
问题描述
是否可以根据对象的实例定义类型?
我不想先定义接口,我想要一个将值作为输入的泛型类型,而不是类型。
例子:
const someObject: any = {
foo: "",
bar: ""
}
// should show error because "bar" property is missing
const someOtherObject: SameShape<someObject> {
foo: ""
}
我现在只需要一个扁平的对象结构。所以像这样的东西(除了有效的东西):
type SameShape = { [key in keyof someObject]: string }
解决方案
使用typeof
运算符。
// This is valid
const someOtherObject: SameShape<typeof someObject>
type SameShape<T> = { [key in keyof T]: string }
但是您需要先将其删除any
。someObject: any
现在对于您的用例,以下就足够了,您不需要额外的SameShape
const someOtherObject: typeof someObject = {/* ... */}
推荐阅读
- shell - 案例:C shell 中 switch 参数过多错误
- r - 从 R 脚本循环 tbl_regression 不为 rmarkdown::render 打印
- javascript - Javascript-Resolve 对 HTML 的承诺
- node.js - 节点检查器离线?
- wordpress - 如何更改折线图和条形图(highcharts / wordpress)的颜色?
- logging - 如何在 AWS Glue 工作人员(内部地图功能)中记录消息?
- php - 将收银员模型从用户更改为酒店
- intellij-idea - 如何在 VSCode 中智能地重新缩进和重新格式化代码?
- mongodb - $elemMatch 不适用于 MongoDB 中的嵌套文档
- python - 如何在python中对流进行部分分区?