【问题标题】:Why the first parameter is type of User why not string ? Typescript can anyone explain me why when为什么第一个参数是用户类型,为什么不是字符串?打字稿谁能解释我为什么
【发布时间】:2021-02-24 02:42:24
【问题描述】:
type User = {
  id: number;
  title: string;
};
function createAction<T>(type: string) {
  return (payload: T) => ({ type, payload })
}

const createUser = createAction<User>("noob");

const result = createUser({ id: 1, title: "sdf" })
console.log(result.payload)

当我调用 createUser 时,它需要用户类型而不是字符串的参数

【问题讨论】:

    标签: typescript function generics types


    【解决方案1】:

    你有这个功能:

    function createAction<T>(type: string) {
      return (payload: T) => ({ type, payload })
    }
    

    这个函数返回另一个函数。这个返回的函数是(payload: T) =&gt; ({ type, payload })。请注意,它被注释为接受T 类型的payload

    所以,在const createUser = createAction&lt;User&gt;("noob"); 中,TUser,因此createUser 采用User

    【讨论】:

      猜你喜欢
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      相关资源
      最近更新 更多