Typescript函数接口实现

时间:2017-05-03 07:29:39

标签: typescript

以下似乎有效:

interface IPredicate {
    (s: Product): boolean
    and(IPredicate): IPredicate
    or(IPredicate): IPredicate
}

如果它有效,我该如何实现它,以便大致如下工作:

let a: IPredicate = (s: Something) => true
let b: IPredicate = (s: Something) => false
let c: IPredicate = a.and(b)

1 个答案:

答案 0 :(得分:2)

更冗长:

interface IPredicate<T> {
    (item: T): boolean
    and(p: IPredicate<T>): IPredicate<T>;
    or(p: IPredicate<T>): IPredicate<T>;
}

function createPredicate<T>(source: (item: T) => boolean) {
    let predicate = source as IPredicate<T>;
    predicate.and = (another:IPredicate<T>) => createPredicate((item: T) => source(item) && another(item));
    predicate.or = (another:IPredicate<T>) => createPredicate((item: T) => source(item) || another(item));

    return predicate;
}

type Something = {};

let a: IPredicate<Something> = createPredicate((s: Something) => true);
let b: IPredicate<Something> = createPredicate((s: Something) => false);
let c: IPredicate<Something> = a.or(b);