【发布时间】:2019-02-13 17:05:07
【问题描述】:
假设我有一个对象:
const config = {
initial: 'foo', // must be key of .states
states: {
foo: {},
bar: {}
}
}
如何创建类型定义以便 TypeScript 可以断言 config.initial 是 config.states 的键?例如,
type Config = {
initial?: <key of .states>,
states: {
[K: string]: Config
}
}
function createSomething(config: Config) {
// ...
}
// should NOT compile
createSomething({
initial: 'fake',
states: {
foo: { states: {} },
bar: { states: {} }
}
});
我的想法是我想要一个强类型的配置对象,它的属性在createSomething 函数中相互依赖。这可能吗?
【问题讨论】:
-
Conf应该指的类型是什么?
标签: typescript