TypeScript:如何在类型中引用自己的属性

3

假设我有一个对象:

const config = {
  initial: 'foo', // must be key of .states
  states: {
    foo: {},
    bar: {}
  }
}

我应该如何创建类型定义,以便TypeScript可以断言config.initialconfig.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 类型应该指的是什么? - ethane
1个回答

1
您可以在函数中描述限制。
function createSomething<S, K extends keyof S>(c: { initial: K, states: S }): Config

...
// Type '"c"' is not assignable to type '"a" | "b"'.
// (property) initial: "a" | "b"
createSomething({ initial: 'c', states: { a: {}, b: {} } });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接