Last active
October 28, 2022 14:13
-
-
Save andremichelle/ea643b877d99f3397d01be4332fc97b6 to your computer and use it in GitHub Desktop.
Safe call to optional methods in interface (nice for visitor pattern)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Bar { type: 'bar' = 'bar' } | |
interface Foo { | |
hello?(): string | |
world?(event: Bar, foo: number): string | |
george?(): string | |
} | |
const bar: Foo = { | |
hello: () => 'world', | |
world: (bar: Bar, foo: number) => `bar is ${bar.type} and foo is ${foo}` | |
} | |
const callIfExists = <F extends (...args: any[]) => any> | |
(func: F | undefined, ...args: Parameters<F>): ReturnType<F> | void => | |
{ if (func !== undefined) return func.apply(null, args) } | |
console.log(callIfExists(bar.hello)) | |
console.log(callIfExists(bar.world, new Bar(), 42)) | |
console.log(callIfExists(bar.george)) | |
// These will produce errors | |
// const r: number = callIfExists(bar.hello) | |
// callIfExists(bar.hello, 1) | |
// callIfExists(bar.world) | |
// callIfExists(bar.world, new Bar(), '42') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment