【问题标题】:Difference between property as function and method属性作为函数和方法的区别
【发布时间】:2017-05-30 11:08:04
【问题描述】:

我想知道foobar的区别在以下界面:

interface Test
{
    foo( value: number): string;
    bar: ( value: number ) => string;
}


let x: Test = {
    foo: ( i ) => "",
    bar: ( i ) => "",
};

很明显,第一个是方法,而第二个是属性,但这在语义上是否相同?

编辑:

它似乎并不完全等价。至少对于构造函数方法now,只有第一个语法似乎是有效的:

class Test
{
}

interface TestConstructor
{
    new(): Test;
}

const activator = function( type: TestConstructor )
{
    return new type(); // fine
}

interface TestConstructor2
{
    new: () => Test;
}

const activator2 = function( type: TestConstructor2 )
{
    return new type(); // Error: Cannot use 'new' with an expression whose type lacks a call or construct signature.
}

【问题讨论】:

    标签: typescript interface


    【解决方案1】:

    它们都是等价的。第一个 (foo( value: number): string;) 只是第二个 (foo: ( value: number ) => string;) 的语法糖。如果您想这样定义高级函数,这很有用:

    function test(myFunction: (value: number) => string)

    【讨论】:

    • 但是你能解释一下newkeyword 的区别吗(见上面问题中的编辑部分)?
    猜你喜欢
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2013-08-12
    • 1970-01-01
    • 2022-10-23
    相关资源
    最近更新 更多