网站搜索

泛型 - 在 Typescript 中索引其他属性的属性


我有以下类型:

interface CellsReducer {
    source: number;
    destination: number;
    plan: string;
    duration: number;
    test: []
}

interface BarReducer {
    baz: string;
}

interface AppState {
    cells: CellsReducer;
    bar: BarReducer;
}

我想编写一个包含以下对象的接口:

interface Props {
    store: keyof AppState;
    field: // AppState[store]
    data: // AppState[store][field]
}

使用泛型没有让我取得任何进展。在以下示例中,fields 最终的类型是 never:

type Stores<T> = keyof T;
type Fields<T> = keyof T[Stores<T>];
type Props<TState> = {
    state: Stores<TState>;
    field: Fields<TState>
}

有办法做到这一点吗?

答案#1

您需要为路径中的每个属性使用不同的类型参数。这允许编译器推理您指定的具体字段:

type Props<TState, KStore extends keyof TState, KField extends keyof TState[KStore]> = {
    state: KStore;
    field: KField
    data: TState[KStore][KField]
}

let p: Props<AppState, "cells", "duration"> = {
  state: "cells",
  field: "duration",
  data: 1
}

你得到 never 的原因是,当编译器尝试展开 AppState[keyof AppState] 时,它会得到一个联合类型 CellsReducer | BarReducer。由于只有联合类型的公共成员是可访问的,keyof (CellsReducer | BarReducer) 是 never(没有键是可访问的)。

额外的参数捕获实际的字段,所以如果 KStore 是字符串字面量类型 "cells",则 keyof AppState["cells"] 将是应用状态中该特定字段的键。KField 的工作方式类似,使我们能够正确地对 data 进行类型定义。

为了避免重复指定 state 和 field 的值,你可以编写一个辅助函数:

function propertyFactory<TState>() {
  return function <KStore extends keyof TState, KField extends keyof TState[KStore]>(o: Props<TState, KStore, KField>) {
    return o;
  }
}
let p = propertyFactory<AppState>()({
  state: "cells",
  field: "duration",
  data: 1
})

答案#2

你的意思是:

interface Props<T, K extends keyof T, V extends keyof T[K]> {
    state: keyof T;
    field: T[K];
    data: T[K][V]
}

用法:

const props: Props<AppState, 'cells', 'plan'> = { /* ... */ } ;
const props: Props<AppState, 'bar', 'baz'> = { /* ... */ } ;