类型错误:通用类型不可分配

时间:2019-01-09 16:28:13

标签: typescript

以下代码生成类型错误,我无法理解。有什么想法我做错了吗?

Type '(state: State) => State' is not assignable to type 'Action'.
  Types of parameters 'state' and 'state' are incompatible.
    Type 'S' is not assignable to type 'State'.

错误在第14行(const action: Action = ...)上生成。

interface IState {
  count: number;
}

class State implements IState {
  count: number;
}

type Action = <S>(state: S) => S
type Dispatch = <A extends Action>(action: A) => void

const dispatch = (action: Action) => { }

const action: Action = (state: State) => state

dispatch(action)

我希望State和通用类型S兼容。

TS playground

1 个答案:

答案 0 :(得分:2)

Action代表通用功能。泛型函数表示可以使用满足给定类型参数约束的类型的 any 类型调用它。

因此,此代码编译时没有任何问题:

declare const action: Action;
action({ count: 0 }); //should return  {count :number } 
action({ sum: 0 });//should return  {sum :number } 
action({ msg: "Some text" });//should return  {msg:number } 

问题是您的函数(至少根据其签名)不满足此要求。它接受一个状态并返回一个状态。如上所述,action的要求使其更加灵活。

如果您的函数确实只是一个标识函数,则可以使用any使该函数与签名兼容

const action: Action = (state: any) => state

或者您可以使函数实现通用:

const action: Action = <T>(state: T) => state

如果所需的不是泛型函数(即适用于任何T的函数),而是具有可针对给定类型定制的签名的常规函数​​,则需要将type参数放在Action

type Action<S> = (state: S) => S
type Dispatch = <A extends Action<any>>(action: A) => void

const dispatch = (action: Action<any>) => { }

const action: Action<IState> = (state) => state
    //declare const action: Action;
action({ count: 0 });
action({ sum: 0 }); // error
action({ msg: "Some text" }); // error


dispatch(action)