type Panel = "store" | "logs"
/*
Define reusable type relation
*/
type PanelRelation<K extends Panel, V> = { [key in K] : V }
/*
Define union type describing relation of keys from Panel, to specific value types.
This ensures that specific keys are mapped to and compatible with specific value
types
*/
type PanelMap =
PanelRelation<'store', StoreComponent> &
PanelRelation<'logs', LogsComponent>
/* Usage example */
type LogsComponent = string
type StoreComponent = number
const object:PanelMap = {
"store": 1,
"logs": "x",
// "logs": 1, <-- value type mismatch produces expected error
// "foo": 1, <-- foo key type not in Panel produces expected error
}
5条答案
按热度按时间zqry0prt1#
预定义的Map类型
Record
就是您要查找的类型。这将采用键的联合并创建一个对象类型,其中每个属性都具有指定为类型的第二个参数的类型:bwntbbo32#
枚举和类型的组合来限制键将起作用:
在我的示例中,
ReactChild
等于any
,这只是为了演示的目的。fdx2calv3#
我认为一个enum可以满足你的要求:
k7fdbhmy4#
另一种提供可重用类型的方法可能是定义一个“键到类型”的关系,然后构造一个联合类型
PaneMap
,它描述Panel
中每个键的值类型:fwzugrvs5#
如果你想保留
object
的类型,你可以使用satisfies
操作符(Typescript 4.9+)。object['store']
的类型将是StoreComponent
的类型。