【发布时间】:2020-11-23 19:43:15
【问题描述】:
Typescript 将下面的applyReducer 调用的state 参数键入为unknown。如果我用applyReducer<State> 明确指定类型,它会起作用,但为什么有必要这样做?看起来很清楚类型应该是State。
(打字稿 v4.1.2)
reducerFlow.ts:
type UnaryReducer<S> = (state: S) => S
export const applyReducer = <S>(reducer: UnaryReducer<S>) =>
(state: S) => reducer(state)
foo.ts
interface State { a: number, b: number }
const initialState: State = { a: 0, b: 0 }
// Why is the type of state unknown?
// Typescript can't infer that it is State?
const foo = applyReducer(
state => ({ ...state, b: state.b + 1 })
)(initialState)
【问题讨论】:
-
对你来说很清楚,但 TypeScript 只知道它需要一些东西并返回具有
b属性的东西!initialState的使用是在对applyReducer的调用完成后,不会从中推断出类型。
标签: typescript