功能类型具有多个未命名的功能

时间:2017-12-21 04:17:52

标签: typescript

该场景是由同一界面定义的两个函数类型

type InterfaceB<R, S> = (param1: S, param2: R) => R;
interface InterfaceA<S> {
    <R>(action: R): R;
}
interface InterfaceA<S> {
    <R>(action: InterfaceB<R, S>): R;
}
const x: InterfaceA<string> = (): InterfaceA<string> => {
    var a1: (action: number) => number = (action: number) => { return 1; };
    var a2: (action: (p: string, p2: number) => number) => number = (action: (p: string, p2: number) => number) => { return 2; };
    return { a1, a2 } as any;
};


const result = x("This should take the (action:R) signature since it's a single value")
console.log(result);

代码编译,但问题很少:

  1. 有没有办法避免演员as any
  2. 当调用x时,VsCode显示正确的两个重载,但是,两个函数都没有被调用,结果是一个带有两个对象的对象文字(这有点意义,因为这是我的意思我回来了)。需要改变什么?
  3. enter image description here

1 个答案:

答案 0 :(得分:0)

这种接口的实现可以是单个函数,它根据输入参数类型改变其行为。例如:

 private static void scanForEpubs(File f) {
        File[] file = f.listFiles();


        for (File ff : file) {
            if (ff.isFile() && ff.getName().endsWith(".pdf")) {
                System.out.println(ff.getName());
            }else {
                if(ff.isDirectory()){
                    scanForEpubs(ff);
                }
            }
        }

    }