打字稿功能界面 [英] Typescript Function Interface

查看:81
本文介绍了打字稿功能界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么没有Typescript警告我,我定义的函数与接口声明不匹配,但如果我尝试调用该函数,它会警告我。

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.

interface IFormatter {
    (data: string, toUpper : boolean): string;
};

//Compiler does not flag error here.
var upperCaseFormatter: IFormatter = function (data: string) {
    return data.toUpperCase();
}  

upperCaseFormatter("test"); //but does flag an error here.


推荐答案

接口确保所有实现此功能的函数调用者接口提供所需的参数 - 数据 toUpper

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

因为TypeScript理解JavaScript不介意传递未使用的参数,所以它在实现中巧妙地允许这样做。

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.

示例:您可以替换 IFormatter 实现和代码工作。

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

interface IFormatter {
    (data: string, toUpper : bool): string;
};

var upperCaseFormatter: IFormatter = function (data: string) {
    return data.toUpperCase();
}

var variableCaseFormatter: IFormatter = function (data: string, toUpper: bool) {
    if (toUpper) {
        return data.toUpperCase();
    }

    return data.toLowerCase();
}

// Switch between these at will
//var formatter = upperCaseFormatter;
var formatter = variableCaseFormatter;

formatter("test", true);

如果TypeScript没有这样做,那么 upperCaseFormatter 必须有一个名为 toUpper 的参数,该参数未在函数中的任何地方使用 - 这使得代码的可读性降低。

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.

这篇关于打字稿功能界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆