如何使用TypeScript编写伪造的useState?

时间:2019-11-19 03:22:49

标签: javascript reactjs typescript

我是刚开始学习TypeScript的菜鸟。

我现在想编写一个虚假的React useState函数进行练习。

现在,我编写了以下代码:

type SetState<S> = ((newState: S) => void) | ((callbackFn: Callback<S>) => void)
type Callback<S> = (prevState: S) => S

function useState<S>(initialState: S): [S, SetState<S>] {
  let state = initialState;

  const setState = (newState: S | Callback<S>) => {
    if (isFunc(newState)) {
      state = newState(state)
    }else {
      state = newState;
    }
    return state;
  };

  return [state, setState];
}

function isFunc(val: any): val is Function {
  return typeof val === 'function'
}

const [a, setA] = useState(2)

setA(prev => a)

但是vscode给我一个错误:

A parameter of type "(prev: number) => number" cannot be assigned to a parameter of type "number & Callback<number>".
   The type "(prev: number) => number" cannot be assigned to the type "number".

我期望的类型是“ Callback”,但是为什么要推断为“ number&Callback”,为什么还要加上“ number&”呢?

您可以将上面的代码放入vscode中运行。

谢谢大家!

0 个答案:

没有答案