javascript - 如何根据参数类型判断函数类型
问题描述
下面这种情况下,如何根据参数类型来判断函数b
类型
const getData = (a: string, b?: string) => {
const obj: Record<string, string> = JSON.parse(a)
if (b) {
return obj[b]
}
return obj
}
const c = getData("{'kind':'cs'}")
const d = getData("{'kind':'cs'}", 'kind')
预期的:
const c = getData("{'kind':'cs'}") // result: {kind: cs} type: c => Record<string, string>
const d = getData("{'kind':'cs'}", 'kind') // result: cs type: d => string
实际的
const c = getData("{'kind':'cs'}") // result: {kind: cs} type: c => Record<string, string> | string
const d = getData("{'kind':'cs'}", 'kind') // result: cs type: d => Record<string, string> | string
解决方案
您可以使用打字稿的函数重载语法。
function getData(a: string): Record<string, string>;
function getData(a: string, b: string): string;
function getData(a: string, b?: string) {
const obj: Record<string, string> = JSON.parse(a);
if (b) {
return obj[b];
}
return obj;
}
const c = getData("{'kind':'cs'}");
const d = getData("{'kind':'cs'}", "kind");
推荐阅读
- spring - 如何获取使用 springs 中的标准和规范运行的每个选择查询的结果大小?
- android - 如何在android中使用GSON检索jsonArray中的jsonObject
- css - ngStyle 应用了多少次
- java - 关于制作离线词典
- haskell - 返回类型丢失 IO
- java - Jigsaw:将 JRE 与自动模块捆绑在一起
- reactjs - 使用自定义扩展加载资产不起作用
- c++ - QNetworkaccessmanager 对象连接函数不调用
- asp.net - 如何在单个 Web api ASP.NET Core 中发布 json 和文件对象
- javascript - 在返回结果之前等待ajax完成(通用功能)