如何使用函数参数访问类型

时间:2020-09-29 21:47:05

标签: typescript

我一直试图根据函数参数获取特定类型,但是我在打字稿中找不到任何方式。

此“ step”参数实际上是切片中的键

type Slice1 = {
    info: string
}

type Slice2 = {
    info: string
}

type MyAppState = {
    step1: Slice1;
    step2: Slice2;
}

function useStep<T>(step: keyof T): T[typeof step] {
  const [state] = useContext(ExternalContext);
  return state[step];
}

const step1 = useStep<MyAppState>('step1'); <-- **should return Slice1 type**

我想根据键来获取正确的类型。

1 个答案:

答案 0 :(得分:1)

我们是否真的可以MyAppState对您进行硬编码?

function useStep<TKey extends keyof MyAppState>(step: TKey): MyAppState[TKey] {
  const [state] = useContext(ExternalContext);
  return state[step];
}

const step1 = useStep('step1'); // <-- returns Slice1 type

编辑: 由于您不想在类型中对MyAppState进行硬编码,因此可以使用curried function

function useStep<T>() {
  return <TKey extends keyof T>(step: TKey): T[TKey] => {
    const [state] = useContext(ExternalContext);
    return state[step];
  }
}

const step1 = useStep<MyAppState>()('step1'); // <-- returns Slice1 type