Reputation: 87
I have an interface called Autocomplete
where I want to include a method with the following declaration:
export interface Autocomplete {
filterOptions: (name: string) => any[];
}
When I implement my interface it gives me this implementation as an arrow function:
filterOptions: (name: string) => any[];
I need a normal function declaration so at the end I would get:
filterOptions(name:string) {
return any[];
}
How do I need to define my method in the interface so I will get
filterOptions(name:string) {
return any[];
}
instead of an arrow function
filterOptions: (name: string) => any[];
Upvotes: -1
Views: 208
Reputation: 265
I guess you can cast but it looks very weird:
const filterOptions = (function(name) {
return any[];
} as Autocomplete);
Upvotes: 0
Reputation: 2050
export interface Autocomplete {
filterOptions(name: string): any[];
}
class Test implements Autocomplete {
// VSCode implementation
filterOptions(name: string): any[] {
throw new Error("Method not implemented.");
}
}
Upvotes: 1
Reputation: 1073978
If you mean that when you write
class Something implements Autocomplete {
}
and then you use the VS Code "Quick fix" called "Implement interface 'Autocomplete'", you get this:
class Something implements Autocomplete {
filterOptions: (name: string) => any[];
}
then unfortunately I don't think you can change the interface definition to make VS Code write it as a method instead (but keep reading).
Two options for you (the first isn't very satisfying, but...):
Just to get it out of the way, one option is to live with it and edit the resulting code while doing the implementation. It's just a matter of removing the :
after the method name, changing the =>
to :
, and replacing the ;
with {}
(and adding the implementation:
class Something implements Autocomplete {
filterOptions(name: string): any[] {
// ...implementation...
}
}
I had hoped that providing a hint to VS Code by using this: Autocomplete
as the first parameter might help:
// DOESN'T HELP (I'd just hoped it would)
export interface Autocomplete {
filterOptions: (this: Autocomplete, name: string) => any[];
}
but sadly it doesn't.
You could make the interface an abstract class instead:
export abstract class Autocomplete {
abstract filterOptions(name: string): any[];
}
Then when you use the Quick Fix "Implement inherited abstract class" you get:
class Something extends Autocomplete {
filterOptions(name: string): any[] {
throw new Error("Method not implemented.");
}
}
But you may not want to use an abstract class.
Upvotes: 0