首页 > 解决方案 > 如何根据参数类型判断函数类型

问题描述

下面这种情况下,如何根据参数类型来判断函数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

标签: javascriptreactjstypescript

解决方案


您可以使用打字稿的函数重载语法。

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");

推荐阅读