首页 > 解决方案 > 如何将强类型添加到此开关替代功能?

问题描述

const switchcase = (value, cases, defaultCase) => {
  const valueString = String(value);
  const result = Object.keys(cases).includes(valueString)
    ? cases[valueString]
    : defaultCase;
  return typeof result === 'function' ? result() : result;
};

我想了解如何在上面的 JavaScript 函数中添加类型,同时避免使用,any除非必要。我意识到value参数可能是any,但我不确定cases,defaultCase和函数的返回类型。

提前致谢!

标签: typescripttypes

解决方案


函数的返回类型取决于您期望返回的内容。

不过,这是一种看法。您需要修改ExpectedReturnType以反映您希望从函数中得到什么,并且您的案例需要是该类型,或者需要是具有 0 元数并返回您预期的返回类型的函数。

interface ExpectedReturnType {}

// Each case is either a function that produces the return type
// or the type itself
type CaseType = ExpectedReturnType | (() => ExpectedReturnType);

const switchcase = (
  value: any,
  cases: { [key: string]: CaseType },
  defaultCase: CaseType
): ExpectedReturnType => {
  const valueString = String(value);
  const result = valueString in cases ? cases[valueString] : defaultCase;
  return typeof result === "function" ? result() : result;
};

您还可以使用泛型:

function switchcase<T, U = T | (() => T)>(
  value: any,
  cases: { [key: string]: U },
  defaultCase: U
): T {
  const valueString = String(value);
  const result = valueString in cases ? cases[valueString] : defaultCase;
  return typeof result === "function" ? (result as Function)() : result;
}

// And you'd use it like so:
const cases = { foo: "bar", whee: () => "yay" };
switchcase("foo", cases, "bar");

// Or so:
switchcase<string>("foo", cases, "bar");

Typescript 有望T从您传递的参数中推断出来,但您始终可以调用它,就switchcase<SomeType>(...)好像您需要专门键入它一样。


推荐阅读