[英]Define a TypeScript type based on an object?
Is it possible to define a type based on an instance of an object? 是否可以基于对象的实例定义类型?
I don't want to define an interface first, I want a generic type that takes a value as the input, not a type. 我不想首先定义一个接口,我想要一个以值作为输入而不是类型的通用类型。
Example: 例:
const someObject: any = {
foo: "",
bar: ""
}
// should show error because "bar" property is missing
const someOtherObject: SameShape<someObject> {
foo: ""
}
A flat object structure is all I need at the moment. 目前,我只需要一个平面对象结构。 So something like this (except something that works): 所以像这样(除了可行的东西):
type SameShape = { [key in keyof someObject]: string }
Use typeof
operator. 使用typeof
运算符。
// This is valid
const someOtherObject: SameShape<typeof someObject>
type SameShape<T> = { [key in keyof T]: string }
But you need to remove that any
in someObject: any
first. 但是,你需要删除any
在someObject: any
第一。
Now for you use case, following is enough, you don't need an extra SameShape
现在,对于您的用例而言,跟随就足够了,您不需要额外的SameShape
const someOtherObject: typeof someObject = {/* ... */}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.