打字稿函数接口重载

时间:2017-05-15 08:39:51

标签: typescript

我有以下代码。

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个参数或没有参数。我怎么能这样做?

4 个答案:

答案 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"
    };
}