我有以下代码。
interface MySecondInterface<A>{
type: A;
}
interface MyInterface {
(val1:string, val2:string): MySecondInterface<string>;
(): MySecondInterface<string>;
}
const myInterfaceFn: MyInterface = (value1: string, value2:string) => {
return {
type: value1 + value2
};
}
const myInterfaceFn2: MyInterface = () => {
return {
type: "Text"
};
}
您可以找到代码here。 我收到错误
Type '(value: string) => { type: string; }' is not assignable to type 'MyInterface'.
如何创建支持两种方法签名的界面?
基本上,函数的接口带有2个参数或没有参数。我怎么能这样做?
答案 0 :(得分:2)
如何使用type
代替interface
?
interface MySecondInterface<A>{
type: A;
}
type MyInterface = ((val1: string, val2: string) => MySecondInterface<string>) | (() => MySecondInterface<string>);
const myInterfaceFn: MyInterface = (value1: string, value2:string) => {
return {
type: value1 + value2
};
}
const myInterfaceFn2: MyInterface = () => {
return {
type: "Text"
};
}
答案 1 :(得分:1)
我不太确定为什么TypeScript可以使用你的接口声明,因为这两个签名没有任何共同之处。也许这是因为TypeScript如何处理函数签名(参见下面的旁注)。
在你的情况下,我会建议
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(64), nullable=False)
address = db.Column(db.String(64), nullable=False)
db.UniqueConstraint('name', 'address')
可选或value
旁注: TypeScript在调用签名方面有点奇怪。我想这是因为它想成为JavaScript的超集。以下片段说明了这一点:
interface Result {
type: string;
}
function myFn();
function myFn(val?: string):Result {
if (!val) { return { type: 'foo' }; }
return { type: val };
}
答案 2 :(得分:1)
专注于你的错误
必须允许
Type '(value: string) => { type: string; }' is not assignable to type 'MyInterface'.
MyInterface
个实例接受0
个参数。所以出现以下错误:
const myInterfaceFn: MyInterface = (value1: string, value2:string) => {
return {
type: value1 + value2
};
}
但如果您将两者都标记为可选(例如使用默认参数),则错误消失:
const myInterfaceFn: MyInterface = (value1 = '', value2 = '') => {
return {
type: value1 + value2
};
}
答案 3 :(得分:1)
您的myInterfaceFn
必须满足MyInterface
中的两个功能定义。
以下代码可以正常使用!
interface MySecondInterface<A>{
type: A;
}
interface MyInterface {
(val1:string, val2:string): MySecondInterface<string>;
(): MySecondInterface<string>;
}
const myInterfaceFn: MyInterface = (value1: string = undefined, value2:string = undefined) => {
return {
type: value1 !== undefined && value2 !== undefined
? value1 + value2
: "Text"
};
}
const myInterfaceFn3: MyInterface = () => {
return {
type: "Text"
};
}