Function property vs method

前端 未结 4 2023
春和景丽
春和景丽 2020-11-30 11:00

What practical differences are there between defining an interface method:

interface Foo {
    bar(): void;
}

and defining a property with

4条回答
  •  北海茫月
    2020-11-30 11:24

    There is another difference, in that the readonly modifier cannot be applied to methods. Therefore, the following assignment cannot be prevented:

    interface Foo {
        bar(): void;
    }
    
    declare var x: Foo;
    x.bar = function () { };
    

    If bar is defined as a property, then the readonly modifier can be applied to it:

    interface Foo {
        readonly bar: () => void;
    }
    

    preventing reassignment.

    (Playground)

提交回复
热议问题