Declare a delegate type in Typescript

前端 未结 5 682
走了就别回头了
走了就别回头了 2021-01-30 10:12

Coming from a C# background, I want to create a datatype that defines a function signature. In C#, this is a delegate declared like this:

delegate v         


        
5条回答
  •  梦如初夏
    2021-01-30 10:43

    You can create something like a delegate by using a type alias:

    type MyDelegate = (input: string) => void;

    which defines a type name for a function pointer, just as delegates do in C#. The following example uses it in combination with generic type parameters:

    type Predicate = (item: T) => boolean;
    
    export class List extends Array {
        constructor(...items: T[]){
            super();
            for(let i of items || []){
                this.push(i);
            }
        }
        public hasAny(predicate?: Predicate): boolean {
            predicate = predicate || (i => true)
            for(let item of this) {
                if(predicate(item)) return true;
            }
            return false;
        }
    }
    

提交回复
热议问题