Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 函数语句中接口的实现_Typescript - Fatal编程技术网

Typescript 函数语句中接口的实现

Typescript 函数语句中接口的实现,typescript,Typescript,在Typescript中,我们可以让一个函数实现如下接口: interface ISample { (argument: boolean): number } let v: ISample; v = function (isTrue: boolean): number { return 10; } 但这仅适用于通过函数表达式创建的函数(即,通过变量初始化它们,在本例中是v)。当我尝试执行类似于函数语句的操作时,它不起作用: interface ISample { (a

在Typescript中,我们可以让一个函数实现如下接口:

interface ISample {
    (argument: boolean): number
}

let v: ISample;
v = function (isTrue: boolean): number {
    return 10;
}
但这仅适用于通过函数表达式创建的函数(即,通过变量初始化它们,在本例中是
v
)。当我尝试执行类似于函数语句的操作时,它不起作用:

interface ISample {
    (argument: boolean): number
}

function v: ISample (isTrue: boolean): number {
    return 10;
} // Doesn't work, compiler says '"(" expected'

那么,有没有一种方法可以通过函数语句来实现这一点呢?或者,如果运气不好,我将不得不放弃接口函数,或者改用函数表达式?谢谢

接口在那里,因此您可以要求变量、参数或字段符合接口。您可以使用函数语句声明函数,然后在需要
ISample
的任何位置分配它

interface ISample {
    (argument: boolean): number
}

function v(isTrue: boolean): number {
    return 10;
} 
let weNeedSample: ISample = v;
不能强制函数语句符合当前typescript语法中的接口。只有当您尝试将函数分配给类型为
ISample
的符号时,才会出现错误


这也是使用函数表达式时发生的情况。在这种情况下,发生错误的原因是,如果您只有函数表达式(例如使用IFFE),则执行对类型为
ISample
的变量的赋值您也不能指定必须符合接口。

接口在那里,因此您可以要求变量、参数或字段符合接口。您可以使用函数语句声明函数,然后在需要
ISample
的任何位置分配它

interface ISample {
    (argument: boolean): number
}

function v(isTrue: boolean): number {
    return 10;
} 
let weNeedSample: ISample = v;
不能强制函数语句符合当前typescript语法中的接口。只有当您尝试将函数分配给类型为
ISample
的符号时,才会出现错误


这也是使用函数表达式时发生的情况。在这种情况下,发生错误的原因是您对类型为ISample的变量执行赋值,如果您只有函数表达式(例如带有IFFE),您也不能指定该表达式必须符合接口。

您可以像这样将函数delcaration强制转换到接口

interface ISample {
  (argument: boolean): number
}

<ISample>function v(isTrue) { // isTrue is a boolean and return type is number
  return 10;
}
接口很简单{
(参数:布尔):数字
}
函数v(isTrue){//isTrue是一个布尔值,返回类型是number
返回10;
}

您可以像这样将函数delcaration强制转换到接口

interface ISample {
  (argument: boolean): number
}

<ISample>function v(isTrue) { // isTrue is a boolean and return type is number
  return 10;
}
接口很简单{
(参数:布尔):数字
}
函数v(isTrue){//isTrue是一个布尔值,返回类型是number
返回10;
}

因此,建议我执行该语句,然后将其分配给实现接口的变量,以便对其进行测试?@Rafael您可以这样做,但问题是为什么希望它符合接口?可能是因为在代码中的某个地方,您实际上会尝试将其分配给这种类型的变量,而这正是您会得到错误的地方。@Rafael添加了一些解释。因此,建议我执行该语句,然后将其分配给实现接口的变量,以便对其进行测试。@Rafael您可以这样做,但问题是,为什么您希望它符合接口?可能是因为在代码中的某个地方,您实际上会尝试将其分配给这种类型的变量,而这正是您将得到错误的地方。@Rafael补充了一些解释