【发布时间】:2019-04-10 18:08:39
【问题描述】:
我在项目中遇到了一些我完全不清楚的问题
// =========================== RxJS types imitation ===========================================================
interface Subscription {
unsubscribe(): void
}
type Subscribe<T> = (value: T) => void
interface Observable<T> {
subscribe(subscribe: Subscribe<T>): Subscription
}
interface Subject<T> {
next(value: T): void
subscribe(subscribe: Subscribe<T>): Subscription
}
// =========================== My custom types ===========================================================
export interface Reducer<S, A> {
(state: S, action: A): S;
}
export interface Effect<A, S> {
(action$: Subject<A>, state$: Observable<S>): Subscription;
}
export interface OptionalParams<S, A> {
effects?: Effect<A, S>[];
}
// =========================== Reproducing concrete types and variables ===========================================================
const initialState = {
some: true
}
type State = typeof initialState
interface BaseAction<T extends string> {
type: T
}
interface ActionA extends BaseAction<"A"> {
payload: string
}
interface ActionB extends BaseAction<"B"> {
payload: number
}
interface ActionC extends BaseAction<"C"> {
payload: boolean
}
declare const reducer: Reducer<State, ActionA | ActionB | ActionC>
declare const outerAction$: Observable<ActionA | ActionB>
declare function createState$<S, A>(
reducer: Reducer<S, A>,
initialState: S,
outerAction$: Observable<A>,
optionalParams?: OptionalParams<S, A>,
): Observable<S>
// =========================== Reproducing the problem ===========================================================
const state$1 = createState$(reducer, initialState, outerAction$)
declare const someEffect: Effect<ActionA | ActionB | ActionC, State>
const state$2 = createState$(reducer, initialState, outerAction$, {
effects: [
someEffect,
]
})
如果启用--sctrictFunctionTypes 选项,悬停在最后一节中的createState$ 函数将显示泛型A 不是类型ActionA | ActionB | ActionC 而是ActionA | ActionB。我不明白--sctrictFunctionTypes 如何影响联合推理。我认为打字稿会尝试推断最常见的联合类型。这方面的知识对我来说很重要,因为我需要将 action$ 参数的类型设为 Subject<ActionA | ActionB | ActionC>,才能将我的效果定义为内联箭头函数。不仅如此:如果我在someEffect 下方添加箭头功能效果,我会在我的项目中从 typescript (v3.1+) 中收到错误消息Types of property 'effects' are incompatible。
谢谢。
【问题讨论】:
标签: typescript