Typescript Function Interface

前端 未结 1 1585
慢半拍i
慢半拍i 2020-12-24 10:34

Why doesn\'t Typescript warn me that the function I am defining does not match the interface declaration, but it does warn me if I try to invoke the function.



        
相关标签:
1条回答
  • 2020-12-24 11:03

    The interface ensures that all callers of functions that implement the interface supply the required arguments - data and toUpper.

    Because TypeScript understands that JavaScript doesn't mind if you pass arguments that aren't used, it cleverly allows this in implementations.

    Why is this okay? Because it means you can substitute any implementation of the interface without affecting calling code.

    Example: You can substitute either IFormatter implementation and the code works.

    interface IFormatter {
        (data: string, toUpper: boolean): string;
    };
    
    var upperCaseFormatter: IFormatter = function (data: string) {
        return data.toUpperCase();
    }
    
    var variableCaseFormatter: IFormatter = function (data: string, toUpper: boolean) {
        if (toUpper) {
            return data.toUpperCase();
        }
    
        return data.toLowerCase();
    }
    
    // Switch between these at will
    //var formatter = upperCaseFormatter;
    var formatter = variableCaseFormatter;
    
    formatter("test", true);
    

    If TypeScript didn't do this, your upperCaseFormatter would have to have to have a parameter called toUpper that wasn't used anywhere in the function - which makes the code less readable.

    0 讨论(0)
提交回复
热议问题