【问题标题】:how to check a function's type in typescript? [duplicate]如何在打字稿中检查函数的类型? [复制]
【发布时间】:2019-07-30 04:20:48
【问题描述】:
type AssertFuncSync = (...args: any[]) => boolean
type AssertFunc = (...args: any[]) => Promise<boolean>

我在上面的 typescript 中定义了两种类型。

现在,在函数demoFunc 中,我需要检查参数是AssertFuncSync 还是AssertFunc。我怎样才能实现它?

const demoFunc = (test_func: AssertFunc | AssertFuncSync): any => {
    if (test_func is an AssertFunc) {
        console.log("it belongs to AssertFunc")
    }else{
        console.log("it belongs to AssertFuncSync")
    }
}

【问题讨论】:

标签: typescript


【解决方案1】:

您可以在您的类型中使用判别属性。这意味着您必须在两种类型中都拥有相同的密钥,然后只需询问该密钥即可。 typescript 可以在预编译时间缩小类型,(而不是在 runetime ofc)

type AssertFuncSync = {
  isSync: true,
  syncFunc: (...args: any[]) => boolean,
};

type AssertFunc = {
  isSync: false,
  asyncFunc: (...args: any[]) => Promise<boolean>,
};

const demoFunc = (testFunc: AssertFunc | AssertFuncSync): any => {
  switch (testFunc.isSync) {
    case true:
      testFunc.syncFunc(); // no error
      testFunc.asyncFunc(); // error: Property 'asyncFund' does not exist on type 
                                     'AssertFuncSync'.
      break;
    case false :
      testFunc.syncFunc(); // error: Property 'syncFunc' does not exist on type 
                                     'AssertFunc'
      testFunc.asyncFunc();  // no error
  }
};

check this out

正如您所提到的,这太冗长了。你可以使用 if 语句代替 switch case...

const demoFunc = (testFunc: AssertFunc | AssertFuncSync): any => {
  if (testFunc.isSync) {
    testFunc.syncFunc(); // no error
  } else {
    testFunc.asyncFunc();  // no error
  }
};

【讨论】:

  • 是的,我认为它会起作用。但是这种方法也会让这个 API 变得非常冗长……
  • 我不知道有什么更好的解决方案。
【解决方案2】:

为了实现这一点,我相信您可以使用 typescripts 的类型保护功能。docs here

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}

function isFish(pet: Fish | Bird): pet is Fish {
    return (<Fish>pet).swim !== undefined;
}

【讨论】:

    猜你喜欢
    • 2020-09-21
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2018-05-22
    相关资源
    最近更新 更多