是否可以为名称指定功能签名?
例如,某些外部模块提供了一个接口
interface MyLocalInterface {
someMethodName typeof ExtFunctionInterface
}
我想创建一个本地接口或抽象类,将上面的接口签名分配给方法名称。例如:
abstract class MyLocalAbstractClass {
public abstract someMethodName typeof|signature of ExtFunctionInterface
}
或
class MyClass {implements|extends} MyLocal{Interface|AbstractClass} {
// Correct impl
public someMethodName(arg1: string, arg2: number): boolean {
// impl
}
// Compiler would complain that the function is not implemented
// correctly because "arg2" is missing or type is wrong for e.g.
public someMethodName(arg1: string): boolean {
// impl
}
}
这样当实现接口或扩展类时:
library(data.table
hh = setDT(read.table(text = "
date strike_price impl_volatility moneyness
1996-09-03 65000 0.192926 0.9431225
1996-09-03 65000 0.184757 0.9431225
1996-09-03 55000 0.190826 0.7980267
1996-09-03 60000 0.187024 0.8705746
1996-09-03 62500 0.189573 0.9068485
1996-09-03 72500 0.209731 1.0519443
2009-10-30 27500 0.646013 0.8107311
2009-10-30 20000 1.261644 0.5896226
2009-10-30 25000 0.835957 0.7370283
2009-10-30 30000 0.462221 0.8844340
2009-10-30 17500 1.512000 0.5159198
2009-10-30 22500 1.038973 0.6633255", header = T))
这意味着当更改ExtFunctionInterface时,编译器会通知签名不正确。
答案 0 :(得分:1)
对于接口,答案比您预期的更简单,只需在接口上声明一个字段,您就会得到所需的行为:
interface MyLocalInterface {
someMethodName : ExtFunctionInterface
}
class MyClassFromInterfce implements MyLocalInterface {
// Will satisfy the interface
public someMethodName (arg1: string, arg2: number): boolean {
return false;
}
// Will not satisfy the interface parameter is of the wrong type
public someMethodName(arg2: number): boolean {
return false;
}
}
对于抽象类,您可以定义一个抽象字段,遗憾的是您无法将其实现为成员函数,您需要将其作为包含该函数的字段来实现,在大多数情况下这应该是一个好的解决方法:
abstract class MyLocalClass {
abstract get someMethodName() : ExtFunctionInterface
}
class MyClass extends MyLocalClass {
// Ok
public someMethodName = (arg1: string, arg2: number): boolean => {
return false;
}
// Not ok
public someMethodName = (arg2: number): boolean => {
return false;
}
}
注意在问题中,您希望编译器在参数较少时发出警告,这不是typescript检查函数兼容性的方式(不仅仅是在这种情况下,而且通常)。具有较少参数的函数将与需要更多参数的签名兼容。 Typescript会警告参数类型不匹配。例如:
class Base {
method(arg1: string, arg2: number) {}
}
class Derived extends Base {
// We can override with fewer parameters
method(arg1: string) {}
// We can't override if parameter types are missmatched
method(arg1: number) {}
// We can override with more parameres if they are optional
method(arg1: string, arg2: number, arg3?: number) {}
// But not if they are required
method(arg1: string, arg2: number, arg3: number) {}
}