Interface injection using an "anonymous" method
Given the following interface Fn
,
interface Fn<A> {
(): A
}
it is possible to instantiate an object that implements the interface using the linker
function buildFn<A>( val: A ): Fn<A> {
return () => { return val }
}
Now using the following interface which is valid in Typescript
interface FnString extends Fn<string> {
(): string
toLowerCase(): string
}
how to write a builder function to instantiate an object FnString
?
edit: solution thanks to @basarat
note: refactored String
→ String
in accordance with comment
function builderFn(str: string): FnString {
var fn = <FnString>(() => str)
fn.toLowerCase = str.toLowerCase
return fn
}
source to share
If you want to create an object that is callable and has other functions, the best way to do this is to start with an object function
. However, since the inline inference type does not match the actual type you are building to, you need a type assertion:
interface Fn<A> {
(): A
}
function buildFn<A>( val: A ): Fn<A> {
return () => { return val }
}
export interface FnString extends Fn<string> {
(): string
toLowerCase(): string
}
interface Awesome extends FnString { }
export function builderFn(): Awesome {
var str = ('asdf');
var fn = <Awesome>(() => str);
fn.toLowerCase = str.toLowerCase;
return fn;
}
Also note that it is string
not the same as string
, but string
is an anti-pattern (so I am refactored to string
).
source to share