简体   繁体   English

TypeScript-如何使用任何类型的参数定义函数类型

[英]TypeScript - How to define Function Type having arguments with any Type

I'm new to TypeScript. 我是TypeScript的新手。

I want to define Function Type having arguments with any Type. 我想定义具有任何类型参数的函数类型。 The function may one argument or more than two argument. 该函数可以是一个参数,也可以是两个以上参数。

How should I write? 我应该怎么写?

(args: any) => any

Writing this way above works only when one argument is passed to the function. 仅当将一个参数传递给函数时,以上编写这种方式才有效。

class NotificationCenter {

    private observerList: Array<() => any>;

    constructor() {
        this.observerList = [];
    }

    addObserver(observer: () => any): void {

        this.observerList.push(observer);

    }

}


let notificationCenter: NotificationCenter = new NotificationCenter();

let observer1 = () => {};
let observer2 = (text: string) => {return "observer2"};
let observer3 = (id: number, data: Array<any>) => {return "observer3"};

//This works fine.
notificationCenter.addObserver(observer1);

//Error:Argument of type '(text: string) => string' is not assignable to parameter of type '() => any'.
notificationCenter.addObserver(observer2);

//Error:Argument of type '(id: number, data: any[]) => string' is not assignable to parameter of type '() => any'.
notificationCenter.addObserver(observer3);

You say the function can have one argument or more than two arguments. 您说函数可以有一个参数或两个以上参数。 That sounds like it can have one or 3 or more arguments. 听起来可以有一个或三个或多个参数。 You'll have to overload it then. 然后,您将不得不重载它。

function foo(arg: any): any { /*do work*/ }
function foo(arg: any, arg2: any, ...rest: any[]): any { /*do work*/ }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 typescript 中键入定义 zip function - how to type define a zip function in typescript 为任何 Function React Typescript 定义 prop 的类型 - Define prop's type for any Function React Typescript 如何在 TypeScript 中为模板定义类型? - How to define a type for a template in TypeScript? 如何键入定义解构箭头 function 表达式 arguments? - How to type define destructured arrow function expression arguments? Typescript:如何用布尔值或回调函数定义联合类型? - Typescript: how do you define a union type with boolean or a callback function? 如何在 React TypeScript 中定义一次类型并将其分配给函数和组件? - How to define a type once and assign it to a function and a component in React TypeScript? 如何根据Typescript中的字符串参数定义函数的参数类型? - How to define a function's argument type dependent on string argument in Typescript? React孩子是一个函数:如何正确定义TypeScript类型? - React children is a function: How to define TypeScript type correctly? Typescript:将类型定义为“任何类型除外”而不触发错误? - Typescript: define a type as "any except type" without triggering errors? 如何定义方法参数中使用的 function 回调类型(作为任何 function 类型,不是通用类型) - How to define type for a function callback (as any function type, not universal any) used in a method parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM