打字稿:自引用接口值作为类型

时间:2020-01-23 07:18:37

标签: typescript state-machine typescript-generics

我有一个函数,该函数将与接口匹配的对象数组作为参数。该函数将生成一个带有状态,值的字符串数组和定义转换的对象数组的有限状态机。

我希望(如果可能的话)能够推断过渡数组上的'from'和'to'参数,作为states属性(潜在状态数组)的字面结合。我目前的尝试仅在string接口上将类型缩小为string[]Transition。理想情况下,以下示例中的S应该为'one' | 'two'

interface Transition<S> {
  from: S,
  to: S[],
}

interface StateMachineDescriptor<T> {
  property: string;
  states: T[];
  transitions: Array<Transition<this['states'][number]>>;
}

function fsm<T>(opts: Array<StateMachineDescriptor<T>>) {
  return opts;
}

fsm([{
  property: 'test',
  states: ['one', 'two'],
  transitions: [{
    from: 'one',
    to: ['foo'],
  }]
}])

打字稿的版本是3.7,演示的链接在这里:

https://www.typescriptlang.org/play/?ssl=23&ssc=4&pln=1&pc=1#code/JYOwLgpgTgZghgYwgAgCpTiAzsMwD2IAPAMoB8yA3gFDLIxT4C2AXMiQDS3Jj5skBtALpcAvtWqhIsRChJg4kALKIAFqAgARCFgRRgAB15QiqCjToHGB6GACebLGH0gA5gG5uTxTraphnnTOmDh4hFhsAIJQGHamGNi4BMRg6lgCAOTekFgZQgIgAK5MAEbQQmRknuLUMIUgCGEg9FhMpmQAFPhGEcjRsaQKymoa2rr6RvgmZmQAlFTcUBBghVDN3WBY1RIwrR0CFshW3bYOyBk5YBlcdNm+yJmEENfnYADu+Hk3PAmhyb0Hbh0BjMNgZJ7XIE8PgPDIwfCfETcURCago2ZAA

0 个答案:

没有答案