typescript - 如何将强类型添加到此开关替代功能?
问题描述
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
和函数的返回类型。
提前致谢!
解决方案
函数的返回类型取决于您期望返回的内容。
不过,这是一种看法。您需要修改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>(...)
好像您需要专门键入它一样。
推荐阅读
- ios - Swift 4 AVcapturesession 不调用 captureOutput 委托
- jenkins - maven PMD插件生成xml格式错误的xml
- python - 错误:Python Range 对象不可调用
- python - 将图像写入文件夹
- linux - 我们如何识别文件中与特定关键字或终端中的字符串匹配的行号?
- java - 在 android 8.0 和 7.0 设备中,WebView 下载 index.php 而不是 pdf 文件
- vue.js - 如何在没有 v-on 指令的情况下从发出事件中获取价值?
- python - PyQt 在 Designer 中看起来不像
- c# - 如何使用 C# 中的 Moq 模拟具有另一个类作为参数的构造函数的具体类
- java - 对于官方 Maven 存储库,人们会发布胖罐子吗?