具有泛型参数类型的接口树

时间:2021-03-01 10:40:49

标签: typescript generics interface tree

我正在为带有泛型类型参数的接口树做一些类型定义。基本上,假设我有以下界面:

interface Foo<S> {
   state: S
   fn: (state: S) => void
}

interface FooTree {
  [key: string]: Foo<any>
}

const tree: FooTree = { bar: { state: { something: 3, fn: (state) => {} } } }

我想要的是基于实际状态对象值键入 fn 方法的 state 参数。这甚至可能吗?目前,我只得到未知/任何

1 个答案:

答案 0 :(得分:0)

这是否符合您的要求:

interface Foo<S> {
    state: S
    fn: (state: S) => void
}

interface FooTree {
    [key: string]: Foo<{ age: number }>
}

const tree: FooTree = { bar: { state: { age: 42 }, fn: (state) => { } } }

Playground

相关问题