Function property vs method
The most critical difference is actually that using the property approach typescript actually checks contravariently for types. For Eg:
type FProp<A> = {
fork: (a: A) => void
}
type FMeth<A> = {
fork(a: A): void
}
type Cat = {
isPurring: boolean
}
type Dog = {
isBarking: boolean
}
const dd = { fork: (a: Cat & Dog) => void 0 }
const fa: FProp<Cat> = dd // will throw up
const fb: FMeth<Cat> = dd // will not issue any error
This is documented —
The stricter checking applies to all function types, except those originating in method or constructor declarations. Methods are excluded specifically to ensure generic classes and interfaces (such as Array) continue to mostly relate covariantly.
https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html
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)
If these are the only declarations, these are identical.
The only difference is that you can augment the first form in a second declaration to add new signatures:
// Somewhere
interface Foo {
bar(): void;
}
// Somewhere else
interface Foo {
bar(s: number): void;
}
// Elsewhere
let x: Foo = ...
x.bar(32); // OK