Typescript:函数是否可能返回动态字符串文字类型?

时间:2019-02-15 03:45:21

标签: typescript redux

在打字稿中,函数可以借助泛型从其参数推断类型,因此它可以返回所传递参数的字符串文字类型。

export function getActionType<T>(actionType: T): T {
  return actionType;
}

const actionType = getActionType("GET_PRODUCTS"); // actionType: "GET_PRODUCTS"

但是,我一直在尝试找出没有成功传递参数的情况,该函数如何在不传递参数的情况下返回动态字符串文字类型。基本上,我想要的是一个返回Redux异步操作类型的函数,该类型由invokedpendingfulfilledrejected类型组成。使用者只需要传递baseActionType即可,它将为其他人加上正确的词后缀,并且每个人都应返回正确的字符串文字类型。

// what should be SomeType?
export function getAsyncActionTypes<T>(baseActionType: T): SomeType {
  return {
    invoked: baseActionType,
    pending: baseActionType + "_PENDING",
    fulfilled: baseActionType + "_FULFILLED",
    rejected: baseActionType + "_REJECTED"
  };
}

// ideal usage, but can't figure out implementation
const actionTypes = getAsyncActionTypes("GET_PRODUCTS");
const invokedType = actionTypes.invoked // invokedType: "GET_PRODUCTS";
const pendingType = actionTypes.pending // pendingType: "GET_PRODUCTS_PENDING";
const fulfilledType = actionTypes.fulfilled // fulfilledType: "GET_PRODUCTS_FULFILLED";
const rejectedType = actionTypes.rejected // rejectedType: "GET_PRODUCTS_REJECTED";

如果这是不可能的,请采取任何解决方法。我最坏的情况是消费者需要自己传递所有异步操作类型。

0 个答案:

没有答案