【问题标题】:TypeScript: relate to own property in typeTypeScript:与类型中的自身属性相关
【发布时间】:2019-02-13 17:05:07
【问题描述】:

假设我有一个对象:

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 应该指的类型是什么?

标签: typescript


【解决方案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: {} } });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多