English 中文(简体)
如何界定具有接受多种类型参数的职能类型?
原标题:How to define the type of function with a parameter that accepts multiple types?
  • 时间:2023-10-06 13:28:41
  •  标签:
  • typescript

This is a simplified version of my code. I want to define the type HandlerFunctionType.

let handlerFunction: HandlerFunctionType;

// handlerFunction will be assigned with one of the following
// case 1
handlerFunction = (value: boolean) => {
  // do something
  return true; // or false
};

// case 2
handlerFunction = (value: number) => {
  // do something
  return true; // or false
};


// case 3
handlerFunction = (value: string) => {
  // do something
  return true; // or false
};

我可以这样界定:

export type HandlerFunctionType =
  | ((value: boolean) => boolean)
  | ((value: number) => boolean)
  | ((value: string) => boolean);

既然这样使法典更长,而且所有这些职能都能够归还一个ool子,我想通过这样做简化:

export type HandlerFunctionType = (value: boolean | number | string) => boolean;

But, this raises error: Type (value: boolean) => true is not assignable to type HandlerFunctionType . Types of parameters value and value are incompatible. Type string | number | boolean is not assignable to type boolean . Type string is not assignable to type boolean .

我如何简化和分类这些类型?

问题回答

在你给出的简化例子中,你指派了一个新的职能,即<代码>handlerFunction 3倍。 在最后一项转让之后,手递功能为(价值:string)=>boolean。 这意味着唯一有效的输入类型string

当你界定<条码>时 类型=(价值:海螺旋式样)=>boolean,是指类型<代码>的机能 类型收到一个参数,即 either a boolean, a string or a number。

handlerFunction 只有在以下情况下才能获得直观参数:handlerFunction,且具有不同类型,例如handlerFunction(1),行为将定下(就文字汇编者而言)。 因此,当你试图宣布<代码>handlerFunction<>/code>为<代码>HandlerFunction>类功能时,版本汇编者回归错误。 类型

我假设你正在尝试使用overload signature,如果是,界定handlerFunction/code>的正确方式。 将:

function handlerFunction(value: string): boolean
function handlerFunction(value: number): boolean
function handlerFunction(value: boolean): boolean
function handlerFunction(value: boolean | number | string) {
  // do something
  return true; // or false
}

然后,你可以界定<条码>。 类型类似:

type HandlerFunctionType = {
    (value: string): boolean;
    (value: number): boolean;
    (value: boolean): boolean;
}

这样,<代码>handlerFunction将接受三种类型的任何参数和<代码>的类型。 HandlerFunctionTypehandlerFunction将匹配。





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签